在 PHP 中运行 MySQL \*.sql 文件

新手上路,请多包涵

我有两个 *.sql 我在创建新网站数据库时使用的文件。第一个文件创建所有表。第二个文件填充了一些默认记录。我想从 PHP 执行这些文件。我也使用 Zend_Framework,如果这将有助于实现这一点。

附加信息

  1. 我没有控制台访问权限
  2. 我正在尝试从我们的应用程序中自动生成站点。

解决方案

使用 shell_exec()

 $command = 'mysql'
        . ' --host=' . $vals['db_host']
        . ' --user=' . $vals['db_user']
        . ' --password=' . $vals['db_pass']
        . ' --database=' . $vals['db_name']
        . ' --execute="SOURCE ' . $script_path
;
$output1 = shell_exec($command . '/site_db.sql"');
$output2 = shell_exec($command . '/site_structure.sql"');

…我从来没有得到有用的输出,但在 另一个线程 上遵循 了一些建议,最终让它全部工作。我切换到 --option=value 命令格式并使用 --execute="SOURCE ..." 而不是 < 来执行文件。

另外,我从来没有很好地解释 shell_exec()exec() 之间的区别。

原文由 Sonny 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 694
2 个回答

这个问题时不时出现。直接从 PHP 运行 .sql 脚本没有好的解决方案。在某些极端情况下,.sql 脚本中的常见语句无法作为 SQL 语句执行。 For example, the mysql tool has builtin commands that are not recognized by the MySQL Server, eg CONNECT , TEE , STATUS , and DELIMITER

所以我给@Ignacio Vazquez-Abrams 的 回答 +1。您应该通过调用 mysql 工具在 PHP 中运行您的 .sql 脚本,例如使用 shell_exec()


我得到了这个测试:

 $command = "mysql --user={$vals['db_user']} --password='{$vals['db_pass']}' "
 . "-h {$vals['db_host']} -D {$vals['db_name']} < {$script_path}";

$output = shell_exec($command . '/shellexec.sql');


另请参阅我对这些相关问题的回答:

原文由 Bill Karwin 发布,翻译遵循 CC BY-SA 4.0 许可协议

PHP 代码

我在 页面上找到的代码对我有用。 (向下滚动查看评论版本)

 <?php
$conn = new mysqli('localhost', 'root', '' , 'sql_auto_test_table');

$query = '';
$sqlScript = file('sqlFileName.sql');

foreach ($sqlScript as $line)   {

    $startWith = substr(trim($line), 0 ,2);
    $endWith = substr(trim($line), -1 ,1);

    if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
        continue;
    }

    $query = $query . $line . "/*<br>*/";
    if ($endWith == ';') {
        mysqli_query($conn,$query) or die('<div>Problem in executing the SQL query <b>,<br><br>' . $query. '</b><br><br>'.$conn->error.'</div>');
        $query= '';
    }
}
echo '<div>SQL file imported successfully</div>';
?>


潜在的修复

我使用 phpMyAdmin 使用 导出到 SQLWordPress 数据库 测试了这个文件,它运行良好。我必须在 .sql 文件的顶部添加以下行,以避免在某些 DATE 列中出现一些 DEFAULT VALUE 错误。或者,如果您收到类似的错误,您可以在执行 SQL 文件之前尝试执行以下查询。

 SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';

此外,用更好的错误处理机制代替暴力 die() 函数。


解释

如果您愿意,我添加了一些注释行来解释该行为。

 <?php
$conn = new mysqli('localhost', 'root', '' , 'db_name');

$query = ''; //Set an empty query variable to hold the query
$sqlScript = file('mySqlFile.sql'); //Set the sql file location

//Read each line of the file
foreach ($sqlScript as $line)   {

    //Get the starting character and the ending character of each line
    $startWith = substr(trim($line), 0 ,2);
    $endWith = substr(trim($line), -1 ,1);

    //Check for empty or comment lines. (If the line starts with --,/*,// or the line is empty, skip to the next line)
    if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
        continue;
    }

    //Add the line to the query. (Additional optional commented out <br> tag added to query for easy error identification)
    $query = $query . $line . "/*<br>*/";
    //If the line end with a ";" assume the last query has ended in this line
    if ($endWith == ';') {
        //Therefore, try to execute the query. Upon failure, display the last formed query with the SQL error message
        mysqli_query($conn,$query) or die('<div>Problem in executing the SQL query <b>,<br><br>' . $query. '</b><br><br>'.$conn->error.'</div>');
        //Reset the query variable and continue to loop the next lines
        $query= '';
    }
}
//If nothing went wrong, display a success message after looping through all the lines in the sql file
echo '<div>SQL file imported successfully</div>';

/*
If failed with an invalid DEFAULT value for a DATE column error, try adding the following lines to the top of your SQL file. Otherwise, execute these lines before executing your .sql file.
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
*/
?>

原文由 Rashmitha Himath 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题