Update query with PDO and MySQL

后端 未结 3 1780
既然无缘
既然无缘 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.

提交回复
热议问题