doumo0206 2019-07-05 05:36
浏览 130
已采纳

为什么在将数据插入SQL服务器时我的php产生错误?

I'm trying to get PHP to insert POST data from my html form into my SQL Server 2018 on a local machine. I looked at php documentation and follow it but i still don't get it why the code is producing an error. The table name that i'm inserting the data to is called "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 script:

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'. 
    ) 
)
  • 写回答

2条回答 默认 最新

  • douzi9211 2019-07-05 06:18
    关注

    If you are using a reserved keyword in SQL Server (which you can check here). You have to use delimited identifiers.

    This should work:

    $sql = "INSERT INTO [USER] (user_id, password, role) VALUES (?, ?, ?)";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler