来自 .sql 文件的 PDO 运行 脚本

PDO run script from .sql file

如何正确地将 运行 sql 文件插入 MySQL? 尝试使用 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?

脚本未 return 错误,但 table 未创建。

由于这是一个脚本,您可以使用以下代码执行 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
}

如果出现错误,它应该会告诉您哪里出了问题。

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