Update query with PDO and MySQL

后端 未结 3 1767
既然无缘
既然无缘 2020-11-29 06:53

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, $pass         


        
相关标签:
3条回答
  • 2020-11-29 07:10

    This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.

    Here's the difference:

    • INSERT creates a new row. I'm guessing that you really want to create a new row.
    • UPDATE changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.

    So this will probably do what you want:

    $sql = "INSERT INTO `access_users`   
      (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
      VALUES (:firstname, :surname, :email, :telephone);
      ";
    

    Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.

    MySQL also supports an alternative syntax for INSERT:

    $sql = "INSERT INTO `access_users`   
      SET `contact_first_name` = :firstname,
        `contact_surname` = :surname,
        `contact_email` = :email,
        `telephone` = :telephone
      ";
    

    This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.

    0 讨论(0)
  • 2020-11-29 07:12
    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 
    
    0 讨论(0)
  • 2020-11-29 07:19

    Your update syntax is incorrect. Please check Update Syntax for the correct syntax.

    $sql = "UPDATE `access_users` set `contact_first_name` = :firstname,  `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";
    
    0 讨论(0)
提交回复
热议问题