0

我正在尝试掌握 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));

我在这里做错了什么?

4

3 回答 3

1

你有一个逗号,你不应该有一个:

$update = query("UPDATE members SET
firstname = '$firstname',
lastname = '$lastname'  
WHERE id = '$id'" ); 

应该可以,尽管我会在准备好的 SQL 语句中使用参数。

$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));
于 2013-09-27T03:10:10.907 回答
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));
于 2013-09-27T03:12:55.870 回答
0

参数必须是键值数组。字符串键是准备好的 sql 中的关联参数。

$q->execute(array(
  'firstname' => $firstname,
  'lastname' => $lastname
));

并且您缺少“id”参数

此外,查询中的参数应以冒号为前缀

$update = query("UPDATE members SET
  firstname = :firstname,
  lastname = :lastname
  WHERE id = :id" );
于 2013-09-27T03:09:34.993 回答