Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run SQL script via 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) 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) placed the backup.sql script into htdocs folder

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/

What am I missing?

like image 732
Giorgio Avatar asked Mar 19 '23 03:03

Giorgio


1 Answers

$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";

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.

like image 132
Hugo Alves Avatar answered Mar 26 '23 03:03

Hugo Alves