dongqing6755 2018-06-10 14:13
浏览 64

如何使用PHP批量执行包含数千个语句的SQL文件?

I have a .sql file that contains a handful of TRUNCATE, DROP TABLE IF EXISTS and CREATE TABLE statements as well as thousands of INSERT and UPDATE statements.

I'm trying to use PHP to execute all the statements in the file in batch as follows:

$sql = file_get_contents('path/to/sql/file.sql');
$link->($sql);

Where $link is a valid MySQLi DB link. I've also tried swapping out $link->($sql) with $link->multi_query($sql), but neither seem to work.

If it makes any difference, I'm attempting to do this in an XAMPP localhost environment on Windows 10 with PHP 7.1 and MariaDB 15.1.

Does anyone know why this would cause problems and not work?
What's the best way in PHP to execute a SQL file with thousands of statements in it?
Thanks.

  • 写回答

1条回答 默认 最新

  • douxie5930 2018-06-10 19:50
    关注

    Ryan, thanks again for the advice. As you suggested, running the mysql command directly on the SQL file is the way to go.

    The following worked for me:

    shell_exec('C:\\xampp\\mysql\\bin\\mysql.exe -h localhost -u root -ppassword -D db-name "SELECT * FROM table-name;"');
    

    Please note that you don't want a space between the -p option and the password itself. If you don't have a password, then just remove the -p option altogether.

    Edit: The sample command above is a very arbitrary one to demonstrate running the mysql command. If you want to read and execute a bunch of SQL statements in a file, the following is more what you need:

    shell_exec('C:\\xampp\\mysql\\bin\\mysql.exe -h localhost -u root -ppassword -D db-name < C:\\xampp\\htdocs\\path\\to\\file.sql');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入