Reputation: 29
When building my app, I made the create query with no trouble. However, when I copied my PHP from the create file to the update file, I've been getting this error:
UPDATE people SET firstname = 'First', lastname = 'Last', email = '[email protected]', phonenumber = 1234567890 WHERE id = 1'
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''' at line 1
Usually, when I get this error, the error gives me an accurate place to fix up. Can anyone help me find this error?
update.sql:
if (isset($_POST['submit'])) {
require "../resources/config.php";
require "../resources/common.php";
try {
$connection = new PDO($dsn, $username, $password, $options);
$id = $_GET['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phonenumber = $_POST['phonenumber'];
$updated_number = array($firstname, $lastname, $email, $phonenumber);
$sql = sprintf(
"UPDATE %s SET firstname = '$firstname', lastname = '$lastname', email = '$email', phonenumber = $phonenumber WHERE id = %s",
"people",
$id
);
$statement = $connection->prepare($sql);
$statement->execute($updated_number);
header("Location: index.php");
}
catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
Upvotes: 0
Views: 169
Reputation: 2239
Don't use sprintf
for building SQL statements as it opens your code up to SQL Injection attacks, it is better to use prepared statements which would looks something like this:
$sql = "UPDATE `people` SET `firstname` = :firstname, `lastname` = :lastname, `email` = :email, `phonenumber` = :phonenumber WHERE `id` = :id;"
$statement = $connection->prepare($sql);
$statement->bindParam(':firstname', $firstname);
$statement->bindParam(':lastname', $lastname);
$statement->bindParam(':email', $email);
$statement->bindParam(':phonenumber', $phonenumber);
$statement->bindParam(':id', $id);
Upvotes: 1
Reputation: 23892
You have two issues here. The first, and more important is your use of prepared statements. All values in the query itself should be bound. So your query should really be:
$updated_number = array($firstname, $lastname, $email, $phonenumber, $id);
$sql = sprintf("UPDATE %s
SET firstname = ?, lastname = ?, email = ?, phonenumber = ?
WHERE id = ?",
"people");
The second is your sprintf
usage.
WHERE id = %s
The %s
is a string, %d
is for an integer. With correct prepared statements this isn't needed though. If "people"
isn't a variable and being built dynamically I think it would be easier to just build that whole query as a normal string. e.g.
$sql = 'UPDATE people
SET firstname = ?, lastname = ?, email = ?, phonenumber = ?
WHERE id = ?';
Upvotes: 1