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();
}
UPDATE
syntax is wrongWHERE
clause to target your specific rowChange
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
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.
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";
Source: Stackoverflow.com