簡體   English   中英

PHP / MySQL中的UPDATE查詢失敗,錯誤代碼1064,SQLState 42000

[英]UPDATE Query in PHP/MySQL Failing with Error Code 1064, SQLState 42000

在構建我的應用程序時,我毫不費力地進行了創建查詢。 但是,當我將PHP從創建文件復制到更新文件時,出現了以下錯誤:

UPDATE people SET firstname ='First',lastname ='Last',email ='test@mail.com',電話號碼= 1234567890 WHERE id = 1'

SQLSTATE [42000]:語法錯誤或訪問沖突:1064 SQL語法有錯誤; 檢查與您的MariaDB服務器版本相對應的手冊以獲取在第1行的'''附近使用的正確語法

通常,當我收到此錯誤時,該錯誤為我提供了一個正確的修復位置。 誰能幫我找到這個錯誤?

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();
    }
}

您在這里有兩個問題。 首先,也是更重要的是您使用准備好的語句。 查詢本身中的所有值都應綁定。 因此,您的查詢實際上應該是:

$updated_number = array($firstname, $lastname, $email, $phonenumber, $id);
$sql = sprintf("UPDATE %s 
                SET firstname = ?, lastname = ?, email = ?, phonenumber = ? 
                WHERE id = ?",
            "people");

第二個是您的sprintf用法。

WHERE id = %s

%s是字符串, %d是整數。 使用正確的預備語句,這不是必需的。 如果"people"不是變量並且是動態構建的,我認為將整個查詢構建為普通字符串會更容易。 例如

$sql = 'UPDATE people
        SET firstname = ?, lastname = ?, email = ?, phonenumber = ? 
        WHERE id = ?';

不要使用sprintf來構建SQL語句,因為它會使您的代碼容易受到SQL Injection攻擊,最好使用准備好的語句,如下所示:

    $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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM