我卡在了这段小代码上:
$fruit_object = new fruit(1234, 'apple', 'red apple');
try {
$dbh = new PDO('mysql:host=localhost;charset=utf8;dbname=database', 'user', 'password');
$exc = $dbh->prepare("INSERT INTO fruit( type, name) VALUES (:type, :name);");
//$exc->bindParam(':id', $fruit_object->id, PDO::PARAM_INT);
$exc->bindParam(':type', $fruit_object->type, PDO::PARAM_STR);
$exc->bindParam(':name', $fruit_object->name, PDO::PARAM_STR);
$exc->execute();
$dbh = null;
$exc = null;
} catch (PDOException $e) {
//this function just do an echo with static content
$this->error_database($e);
$dbh = null;
$exc = null;
die();
}
我已经使用 PDO 从我的数据库中选择内容,但是对于插入内容,它不起作用。用户只能访问 INSERT 内容 - 我已经在我的后端成功地尝试过了。
所以这里是错误:
Fatal error: Uncaught Error: Cannot access private property fruit_object::$type
这是我的 fruit_object 类:
<?php
class fruit
{
private $id;
private $type;
private $name;
function __construct($id, $type, $name)
{
$this->id = $id;
$this->type = $type;
$this->name = $name;
}
function __toString()
{
return $this->name;
}
}
对于马丁:
INSERT INTO fruit (id, type, name) VALUES (DEFAULT, 'apple', 'red apple');
我的数据库在 MySQL 服务器上运行 - 这是原因吗?我必须使用问号 (?) 吗?
谢谢你,路易斯
最佳答案
你缺少 prepare 和分号的右括号
$exc = $dbh->prepare("INSERT INTO fruit(id, type, name) VALUES (:id, :type, :name)");
如果不工作则添加这一行来检查错误
print_r($exc->errorInfo());
关于PHP PDO - INSERT INTO 与 bindParam 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45633745/