通过 PHP 运行 SQL 脚本 [英] Run SQL script via PHP
问题描述
我创建了一个 backup.sql
脚本来恢复 MySql 数据库.我已经使用 PHPMyAdmin 导入检查了脚本,一切正常(数据库已成功恢复).现在我想通过 PHP 运行它.我找到了这个问题,我有:
I've created a backup.sql
script to restore a MySql database. I've checked the script with PHPMyAdmin import and everything works fine (the database has been restored successfully). Now I would like to run it via PHP. I've found this question and I have:
1) 在 htdocs 文件夹中创建一个 PHP 文件,内容如下
1) created a PHP file into htdocs folder with the following content
$site_path= realpath(dirname(__FILE__)).'/';
$command = 'mysql'
. ' --host=' . 'localhost'
. ' --user=' . 'myuser'
. ' --password=' . 'mypass'
. ' --database=' . 'dbname'
. ' --execute="SOURCE ' . $site_path;
$output = shell_exec($command . 'backup.sql"');
echo "<pre>".$output."</pre>";
2) 将 backup.sql 脚本放入 htdocs 文件夹
2) placed the backup.sql script into htdocs folder
但是当我运行脚本时,数据库没有任何反应,shell_exec 结果也没有显示任何内容.我在 Windows 机器上的 Apache 下运行 PHP 和 MySql.命令变量具有以下值:
But when I run the script, nothing happens on the database and nothing is displayed regarding shell_exec results. I'm running PHP and MySql under Apache on a windows machine. The command variable has the following value:
mysql --host=localhost --user=myuser --password=mypass--database=dbname --execute="SOURCE C:\Programmi\Apache Software Foundation\Apache2.2\htdocs/
我错过了什么?
推荐答案
$mysql_host = "localhost";
$mysql_database = "db";
$mysql_user = "user";
$mysql_password = "password";
# MySQL with PDO_MYSQL
$db = new PDO("mysql:host=$mysql_host;dbname=$mysql_database", $mysql_user, $mysql_password);
$query = file_get_contents("shop.sql");
$stmt = $db->prepare($query);
if ($stmt->execute())
echo "Success";
else
echo "Fail";
如果您的 sql 文件中的整个代码 100% 正确且没有任何更改,请尝试此操作,使用 PDO 以提高代码的安全性.
If you have the whole code in your sql file 100% correct and nothing to change on it, then try this, use PDO for better security in your code.
这篇关于通过 PHP 运行 SQL 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!