Tuesday, 23 May 2017

sql - PHP UPDATE query doesn't submit




I have a form that when submitted, will update existing information in my database. However, the code throws an error once I submit the form. Below is the error and the code that I'm using.





"Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE def SET color = blue WHERE id = '26'; UPDATE def SET msg =
hi" WHER' at line 2




if (!empty($_POST)) {

$conn = new mysqli($host, $user, $password, $database_name);
if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE def SET title = $_POST[title] WHERE id = '$_GET[id]';
UPDATE def SET color = $_POST[color] WHERE id = '$_GET[id]';
UPDATE def SET msg = $_POST[msg] WHERE id = '$_GET[id]';";

if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {

echo "Error updating record: " . $conn->error;
}
$conn->close();
}
?>


Not sure why this is happening, as I've changed the code multiple times and have searched in Stackoverflow with no results.


Answer



You have multiple problems here.





  • You must wrap strings ($_POST['title'], $_POST['color'], $_POST['msg']) in quotation marks or single quotation marks. This is clear from the error you get.




    • Right now, the only one you are wrapping in quotation marks is $_POST['id'], which I assume is a number. That's the only one that doesn't require quotation marks. But, as I point out below, you shouldn't be doing it this way, anyway; it leaves you open to SQL injection attacks.


  • Your named array indexes (title, color, msg, etc.) should be in single quotes: $_POST['title'], not $_POST[title].


  • You are trying to execute multiple queries with one call to $conn->query(). That doesn't work. You would need to call $conn->multi_query(), but you shouldn't because that is harder to test, debug, and maintain. Generally, you should break up your code so that you run one query at a time.





    • But, in this case, you don't need multiple queries in the first place. You can and should update all three columns for the matching row in one UPDATE query.


  • Also, you are wide open to **SQL injection**. You need to use prepared statements, rather than concatenating variables into your query. Simply escaping your variables is not enough. See How can I prevent SQL injection in PHP?.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...