我在IIS和Windows 7中运行MySql + PHP。 这是我用来尝试创建一个新数据库somedb的php代码:
$cmd = escapeshellcmd('mysql -u root -p myPasswd -h localhost -Bse "create database somedb;" ');
$test = shell_exec("C:\\Program^ Files^ ^(x86)\\MySQL\\MySQL^ Server^ 5.6\\bin\\".$cmd);
var_dump($test);
echo "<br>============<br>";
print_r($test);
我只使用var_dump和print_r来检查输出。 运行代码后,我有这个输出:
string 'C:\Program Ver 14.14 Distrib 5.6.23, for Win32 (x86)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Usage: C:\Program [OPTIONS] [database]
-?, --help Display this help and exit.
-I, --help Synonym for -?
--auto-rehash Enable automatic rehashing. One doesn't need to use
'rehash' to get table'... (length=12085)
=========================================================================================
C:\Program Ver 14.14 Distrib 5.6.23, for Win32 (x86) Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Usage: C:\Program [OPTIONS] [database] -?, --help Display this help and exit. -I, --help Synonym for -? --auto-rehash Enable automatic rehashing. One doesn't need to use 'rehash' to get table and field completion, but startup and reconnecting may take a longer time. Disable with --disable-auto-rehash. (Defaults to on; use --skip-auto-rehash to disable.) -A, --no-auto-rehash No automatic rehashing. One has to use 'rehash' to get table and field completion. This gives a quicker start of mysql and disables rehashing on reconnect. --auto-vertical-output Automatically switch to vertical output mode if the result is wider than the terminal width. -B, --batch Don't use history file. Disable interactive behavior. (Enables --silent.) --bind-address=name IP address to bind to...
所以似乎shell_exec可以在bin directotry中调用mysql,但它不是在创建数据库。这不是许可问题。我试图在命令行中使用sql语句创建并且它运行良好。我已经尝试在没有-h localhost的情况下创建,或者为-e或--execute更改-Bse。 我已经尝试了这篇文章Create database in Shell Script - convert from PHP的所有建议,但它对我不起作用。我错过了什么?
=============================================== ============================
只有更新,如果我在Apache + win7中运行,这是一个运行良好的代码:
echo shell_exec("C:\\xampp\\mysql\\bin\\mysql -u root -e \"CREATE DATABASE IF NOT EXISTS somedb\" ");
它创建数据库并在浏览器中不显示任何内容。注意:无论是-u还是root之间的空格。
答案 0 :(得分:0)
为启动器抛弃-u和-p之后的空格。我知道它看起来很奇怪,但是如果你不这样做,mysql会有动脉瘤。
另外如果你还在php中,你为什么要这样做?刚刚从php中取出一个mysql命令而没有shell。如果您拥有的活动连接缺少凭据,请使用具有适当凭据的新连接对象,执行此操作,然后关闭该连接。
这确实让我想到了一个令人尴尬但必要的问题,当你的shell,运行的shell是什么盒子,一台不是服务器的客户端机器?
答案 1 :(得分:0)
好的,我找到了解决方案:
转到php代码并删除mysql的路径。新的shell_exec 应该是这样的:
echo shell_exec(“mysql -umYusername -pmYpassword -e \“创建数据库,如果不存在somedb \”“);
注意:AsConfused很严格。我们必须避免-u和-p
运行代码。应该创建数据库!