简体   繁体   中英

PHP PDO Update SQL Syntax Error

I am new to PDO and I'm trying to build my own CRUDS application. I already created CRD but I'm getting stuck with Updating user information. It seems that I have a problem with my syntax, but I thoroughly checked the documentation and I can't figure out what is wrong with the code. It's passing me this error:

ERROR: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Doe, email=johndoe@gmail.com, location=New York City WHERE id=1' at line 1

Here is my code:

include('database.inc.php');

if (isset($_POST['submit'])) {

$id = $_POST['userId']; // 1
$name = $_POST['employee_name']; // John Doe
$email = $_POST['email']; // johndoe@gmail.com
$location = $_POST['location']; // New York City

    try {

     $query = "UPDATE users SET employee_name=$name, email=$email, location=$location WHERE id=$id";
     $statement = $conn->prepare($query);
     $statement->execute();

     header('Location: ../index.php');

     } catch(PDOException $e) {

    echo 'ERROR: ' .$e->getMessage();

     }

}

The problem with your code is that you didn't put quotes around the string values in the SQL. But you should use parametrized queries, not substitute variables into the SQL. This solves the quoting problem, and also prevents SQL injection.

$query = "UPDATE users SET employee_name=:name, email=:email, location=:location WHERE id=:id";
$statement = $conn->prepare($query);
$statement->execute(array(':name' => $name, 
                          ':email' => $email,
                          ':location' => $location,
                          ':id' => $id));

Try surrounding the variables in the statement with single quotes ( ' )

$query = "UPDATE users SET employee_name='$name', email='$email',
location='$location' WHERE id='$id'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM