不是,这不是重复的!我已经搜索了互联网,其中包括StackOverflow,但没有找到答案,因为他们所有人都没有使用PDO或出于其他无法解决我的问题的原因
所以,这是我得到的错误
致命错误:未捕获错误:在C:\ xampp \ htdocs \ ecommerce \ includes \ form_handlers \ register_handler.php:27中对bool的成员函数execute()进行调用:堆栈跟踪:#0 {main}抛出在C:\第27行上的xampp \ htdocs \ ecommerce \ includes \ form_handlers \ register_handler.php
这是我的联系
$hostname = "localhost";
$username = "root";
$password = "123456";
$dbname = "ecommerce";
// Set DSN (Data Source Name)
$dsn = "mysql:host=" . $hostname . ";dbname" . $dbname;
// Make a PDO instance;
$pdo = new PDO($dsn, $username, $password);
// ATTRIBUTE DEFAULTS
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
这是我的查询方式(我在其中查询了该文件所需的配置,我是PDO的新手,不知道这是否可行!)
if (isset($_POST["first_name"])) {
$first_name = "Hello";
$last_name = "World";
$author = "someone";
$is_published = "true";
$sql = "INSERT INTO posts_1(first_name, last_name, author, is_published) VALUES(:first_name, :last_name, :author, :is_published)";
$stmt = $pdo->prepare($sql);
$stmt->execute(["first_name" => $first_name, "last_name" => $last_name, "author" => $author, "is_published" => $is_published]);
echo "Post added";
}
您能告诉我错误在哪里吗?
错误在$dsn = "mysql:host=" . $hostname . ";dbname" . $dbname;
行上,您缺少方程式符号。将其更改为$dsn = "mysql:host=" . $hostname . ";dbname=" . $dbname;
我也找不到PDO的副本(如果有人可以,请张贴它,所以就可以了...
您的问题是prepare
失败,因此$pdo->prepare
返回false。您需要通过检查返回状态来找出原因,例如:
$sql = "INSERT INTO posts_1(first_name, last_name, author, is_published) VALUES(:first_name, :last_name, :author, :is_published)";
$stmt = $pdo->prepare($sql);
if (!$stmt) {
echo "Prepare failed: {$pdo->errorInfo[2]}";
exit; // or something else appropriate
}