cali17
cali17

Reputation: 3

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 ?

Upvotes: 0

Views: 77

Answers (3)

user1032531
user1032531

Reputation: 26281

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

Upvotes: 1

Fluffeh
Fluffeh

Reputation: 33502

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

Upvotes: 1

Leetbulb
Leetbulb

Reputation: 416

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

Upvotes: 0

Related Questions