I'm getting a syntax error back on a sql insert statement that confuses me. The insert actually happens, but the error is halting the rest of the process.
The server is running PHP 5.6.35, and I'm using mysqli 5.5.59. I have other inserts written in similar fashion that work as expected.
Server Side:
<?php
$db = mysqli_connect('localhost', '******', '******', '******'); //Starred out for posting here
$charName = $_POST['charName'];
$metatype = $_POST['metatype'];
$user_id = $_POST['user_id'];
$sqlStatement = sprintf("insert into characters (name, metatype, user_id) values('%s','%s',%s);",
mysqli_real_escape_string($db, $charName),
mysqli_real_escape_string($db, $metatype),
mysqli_real_escape_string($db, $user_id));
echo $sqlStatement;
$result = mysqli_query($db, $sqlStatement);
if($result == false)
{
echo 'Error Inserting to Database: '.mysqli_error($db);
http_response_code(500);
return;
}
else
{
//Not getting here, more core that should run if no error
}
?>
With the code echoing the sql string back, I get:
insert into characters (name, metatype, user_id) values('Test 45','human',5);
Followed by:
Error Inserting to Database: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
Returning to the character list, the new character is included.
On the database columns, name and metatype are utf8 text types, while user_id is an integer.
Regarding the duplicate flag:
I fail to see how this is a duplicate of the linked question. I'm using a different method for creating the statement, and my statement actually runs without error in everything but mysqli (where it still technically runs). The answer given is the same: "just use prepared statements", which doesn't actually answer the question. I get that they are superior, but as far as I can see, the method I am using is not deprecated in php, and should still work.
Update:
Switching to a prepared statement also yields this error. Code:
$db = new mysqli('localhost', '******', '******', '******');
$charName = $_POST['charName'];
$metatype = $_POST['metatype'];
$user_id = $_POST['user_id'];
$sqlStatement = $db->prepare("insert into `characters` (`name`, `metatype`, `user_id`) values(?,?,?)");
$sqlStatement->bind_param("ssi", $charName, $metatype, $user_id);
$result = $sqlStatement->execute();
if($result == false)
{
echo 'Error Inserting to Database: '.mysqli_error($db);
http_response_code(500);
return;
}
Response:
Error Inserting to Database: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1