PDO从.sql文件运行脚本[重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

如何在MySQL中正确运行sql文件?尝试使用PDO:

$mysql_host = "localhost";
$mysql_database = "planets_test";
$mysql_user = "root";
$mysql_password = "";
# MySQL with PDO_MYSQL
$dbh= new PDO("mysql:host=$mysql_host;dbname=$mysql_database", $mysql_user, $mysql_password);
$query = file_get_contents("planets_db.sql");
$stmt = $dbh->prepare($query);
$stmt->execute();

其中planets_db.sql“是脚本生成的PHPmyAdmin?

脚本不返回错误,但未创建表。

php mysql pdo php-7.2
2个回答
0
投票

由于这是一个脚本,您可以使用以下代码执行SQL:

try {
     $mysql_host = "localhost";
     $mysql_database = "planets_test";
     $mysql_user = "root";
     $mysql_password = "";
     $dbh= new PDO("mysql:host=$mysql_host;dbname=$mysql_database", $mysql_user, $mysql_password);
     $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
     $query = file_get_contents("planets_db.sql");
     $dbh->exec($query);
     print("Created $table Table.\n");

} catch(PDOException $e) {
    echo $e->getMessage();//Remove or change message in production code
}

如果有错误,它应该告诉你出了什么问题。


-1
投票

我在电脑上检查了你的代码。没有发现任何错误。请检查同一目录中的SQL文件或它是否是正确的SQL文件。

© www.soinside.com 2019 - 2024. All rights reserved.