Skip to content
Advertisement

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

Advertisement

Answer

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 (?, ?, ?)";
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement