簡體   English   中英

為什么將數據插入SQL Server時我的php產生錯誤?

[英]Why is my php producing error when inserting data into SQL server?

我正在嘗試讓PHP將html表單中的POST數據插入本地計算機上的SQL Server 2018中。 我看了php文檔並按照它進行操作,但是我仍然不明白為什么代碼會產生錯誤。 我要向其中插入數據的表名稱為“ USER”。 誰能看看我的代碼並告訴我怎么了?

我已經找到了包括PHP.net和堆棧溢出在內的各種資源來尋求解決方案,但並不能幫助我解決問題。

PHP腳本:

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

    $username = strip_tags(trim($_POST["username"]));
    $password = strip_tags(trim($_POST["password"]));
    $role = strip_tags(trim($_POST["role"]));
    $pwdhash = password_hash($password, PASSWORD_ARGON2I);


    $sql = "INSERT INTO USER (user_id, password, role) VALUES (?, ?, ?)";
    $params = array($username, $pwdhash, $role);
    $stmt = sqlsrv_query( $conn, $sql, $params);

    if ($stmt){

        $msg = "Account created successfully!";

    }else{

        die(print_r(sqlsrv_errors(), true));
    }

}

結果:

Array ( 
    [0] => Array ( 
        [0] => 42000 
        [SQLSTATE] => 42000 
        [1] => 156 
        [code] => 156 
        [2] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword 'USER'. 
        [message] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword 'USER'. 
    ) 
)

發布問題后1分鍾后我才發現問題。 “用戶”是SQL Server中的保留關鍵字。 一旦我將表名更改為USERNAME,它就可以工作了!!

如果您在SQL Server中使用保留關鍵字(可以在此處檢查)。 您必須使用定界標識符。

這應該工作:

$sql = "INSERT INTO [USER] (user_id, password, role) VALUES (?, ?, ?)";

暫無
暫無

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

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