简体   繁体   中英

Update query with PDO throws error

I'm trying to get the hang of PDO but I'm getting the following error:

Call to a member function execute() on a non-object

Here's my code to update the members table

$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));

What am I doing wrong here ?

You have a comma where you shouldn't have one:

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

Should work, though I would use params in the prepared SQL statement.

$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));

Your use of parentheses around your variables makes them true/false which is not your intent. Then, the whole point of using prepared statements is not to directly insert data into your queries, but instead either use ? or :someVariable so they will be properly escaped and can be used for multiple inserts. Try something like the following:

$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));

the parameters must be a key value array. string key being the associated parameter in the prepared sql.

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

and you're missing 'id' parameter

also, the parameters in the query should prefix with a colon

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM