Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling MySQL exe using PHP exec doesn't work

Tags:

php

mysql

I have an extremely simple script with PHP exec, calling mysql command:

  $dbhost = 'localhost';
  $dbuser = 'root';
  $dbpass = 'mypass';
  $db = 'job';
  $file ='job_create.sql';
  $mySQLDir='"C:\Program Files\MySQL\MySQL Server 5.1\bin\mysql"';



    if ($dbpass != '') {
        $cmd = $mySQLDir.' -h '.$dbhost.' --user='.$dbuser.' --password='.$dbpass.' < "'.dirname(__FILE__).'\\'.$file.'"';
    } else {
        $cmd = $mySQLDir.' -h '.$dbhost.' --user='.$dbuser.' < "'.dirname(__FILE__).'\\'.$file.'"';
    }

    // echo $cmd;
    exec($cmd,$out,$retval);

I would expect that the above script calls mysql command, pass in the user authentication information and run the job_create.sql on the fly.

The only thing is that it doesn't work, in the sense that the job_create.sql is not run properly. . I tried to call mysql command directly from command line using the below script,

bin\mysql.exe -h localhost --user=root --password=mypass < "job_create.sql"

and it works.

Any idea how to fix this?

Edit: I call this script from PHP command line. i.e., PHP.exe installdb.php

like image 776
Graviton Avatar asked Apr 21 '26 18:04

Graviton


1 Answers

I found the solution

The problem is that you need to explicitly enclosed the $cmd in "".i.e.,

exec('"'.$cmd.'"',$out ,$retval);

This is the full code that works:

<?php

  $dbhost = 'localhost';
  $dbuser = 'root';
  $dbpass = 'password';
  $db = 'job';
  $file =dirname(__FILE__).'\\'.'job_create.sql';
  $mySQLDir='"C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysql.exe"';



    if ($dbpass != '') {
        $cmd = $mySQLDir.' -h '.$dbhost.' --user='.$dbuser.' --password='.$dbpass.' < "'.$file.'"';

    } else {
        $cmd = $mySQLDir.' -h '.$dbhost.' --user='.$dbuser.' < "'.$file.'"';
    }

     echo $cmd;  

   exec('"'.$cmd.'"',$out ,$retval);
   echo "\n";
    echo ($retval);

?>
like image 119
Graviton Avatar answered Apr 24 '26 07:04

Graviton