简体   繁体   English

为什么将数据插入SQL Server时我的php产生错误?

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

I'm trying to get PHP to insert POST data from my html form into my SQL Server 2018 on a local machine. 我正在尝试让PHP将html表单中的POST数据插入本地计算机上的SQL Server 2018中。 I looked at php documentation and follow it but i still don't get it why the code is producing an error. 我看了php文档并按照它进行操作,但是我仍然不明白为什么代码会产生错误。 The table name that i'm inserting the data to is called "USER". 我要向其中插入数据的表名称为“ USER”。 Can anyone look at my code and tell me what's wrong? 谁能看看我的代码并告诉我怎么了?

I have looked various sources including PHP.net and stack overflow for solution but doesn't help me in solving my problem. 我已经找到了包括PHP.net和堆栈溢出在内的各种资源来寻求解决方案,但并不能帮助我解决问题。

PHP script: 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));
    }

}

Result: 结果:

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'. 
    ) 
)

I just found out 1 min later after posting the questions. 发布问题后1分钟后我才发现问题。 "User" is a Reserved Keywords in SQL Server. “用户”是SQL Server中的保留关键字。 Once i changed my table name to USERNAME then it works!! 一旦我将表名更改为USERNAME,它就可以工作了!!

If you are using a reserved keyword in SQL Server (which you can check here ). 如果您在SQL Server中使用保留关键字(可以在此处检查)。 You have to use delimited identifiers. 您必须使用定界标识符。

This should work: 这应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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