Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update query with PDO and MySQL

Tags:

Im trying to write an update query with PDO only I cant get my code to execute?

try {  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   $sql = "UPDATE `access_users`          (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)        VALUES (:firstname, :surname, :telephone, :email);       ";     $statement = $conn->prepare($sql);  $statement->bindValue(":firstname", $firstname);  $statement->bindValue(":surname", $surname);  $statement->bindValue(":telephone", $telephone);  $statement->bindValue(":email", $email);  $count = $statement->execute();    $conn = null;        // Disconnect } catch(PDOException $e) {   echo $e->getMessage(); } 
like image 518
Liam Avatar asked Aug 19 '13 21:08

Liam


People also ask

How to update data in PHP and MySQL?

Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP function mysql_query. Below is a simple example to update records into employee table. To update a record in any table it is required to locate that record by using a conditional clause.

How do I update two columns at a time in MySQL?

MySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.


1 Answers

  1. Your UPDATE syntax is wrong
  2. You probably meant to update a row not all of them so you have to use WHERE clause to target your specific row

Change

UPDATE `access_users`          (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)        VALUES (:firstname, :surname, :telephone, :email) 

to

UPDATE `access_users`       SET `contact_first_name` = :firstname,        `contact_surname` = :surname,        `contact_email` = :email,        `telephone` = :telephone   WHERE `user_id` = :user_id -- you probably have some sort of id  
like image 53
peterm Avatar answered Oct 27 '22 00:10

peterm