gpt4 book ai didi

php - PDO 准备错误

转载 作者:行者123 更新时间:2023-11-29 07:38:42 25 4
gpt4 key购买 nike

public function connect(){
/*connect to data base change to PDO, for securely*/
try{
$connection = new PDO('mysql:host=127.0.0.1;dbname=system', 'root', '' );
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
}catch(PDOException $e){
die('this won\'t work');
}
}

public function insert($table, $fields, $values){
$fields = implode(", ", $fields);
$values = implode("','", $values);
try{
/*what have i done wrong here??*/
$stmt = $this->connection->prepare("INSERT INTO $table(ID, $fields) VALUES ('', '$values')");
$stmt->execute();
return TRUE;
}catch(PDOException $j){
die("Could not send data");
}
}
}

错误:在非对象in上调用成员函数prepare()。prepare存在但为空?

我在这里做错了什么?

最佳答案

您没有存储与该对象的连接。因此,在您的下一个方法中,连接对象丢失了。试试这个:

  try{
$this->connection = new PDO('mysql:host=127.0.0.1;dbname=system', 'root', '' );
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
}catch(PDOException $e){
die('this won\'t work');
}

希望对您有所帮助!

关于php - PDO 准备错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29798762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com