我正试图抓住PDO,但我收到以下错误:
Call to a member function execute() on a non-object
这是我更新members
表的代码
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$update = query("UPDATE members SET
firstname = '$firstname',
lastname = '$lastname',
WHERE id = '$id'" );
$q = $conn->prepare($update);
$q->execute(array($firstname,$lastname));
我在这里做错了什么?
答案 0 :(得分:1)
你有一个逗号,你不应该有一个:
$update = query("UPDATE members SET
firstname = '$firstname',
lastname = '$lastname'
WHERE id = '$id'" );
应该可以工作,不过我会在准备好的SQL语句中使用params。
$update = query("UPDATE members SET
firstname = :FirstName,
lastname = :LastName
WHERE id = :ID" );
$q = $conn->prepare($update);
$q->execute(array(':FirstName' => $firstname, ':LastName' => $lastname, ':ID' => $ID));
答案 1 :(得分:1)
你在变量周围使用括号会使它们成为真/假,这不是你的意图。那么,使用预准备语句的全部意义不是直接将数据插入到查询中,而是使用?或:someVariable,因此它们将被正确转义并可用于多个插入。尝试以下内容:
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$id = $_POST['id'];
$update = query("UPDATE members SET firstname = ?, lastname = ? WHERE id = ?");
$q = $conn->prepare($update);
$q->execute(array($firstname,$lastname,$id));
//OR
$update = query("UPDATE members SET firstname = :firstname , lastname = :lastname WHERE id = :id");
$q = $conn->prepare($update);
$q->execute(array('firstname'=>$firstname,'lastname'=>$lastname,'id'=>$id));
答案 2 :(得分:0)
参数必须是键值数组。 string key是准备好的sql中的关联参数。
$q->execute(array(
'firstname' => $firstname,
'lastname' => $lastname
));
并且您缺少'id'参数
此外,查询中的参数应以冒号前缀
$update = query("UPDATE members SET
firstname = :firstname,
lastname = :lastname
WHERE id = :id" );