Recent Posts

How to solve: MySQL: You have an error in your SQL syntax; check the manual that corresponds...

This error is often caused because you forgot to properly escape the data passed to a MySQL query.
An example of what not to do (the "Bad Idea"):
$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);
This code could be included in a page with a form to submit, with an URL such ashttp://example.com/edit.php?id=10 (to edit the post n°10)
What will happen if the submitted text contains single quotes? $query will end up with:
$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';
And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.
To avoid such errors, you MUST always escape the data before use in a query.
Escaping data before use in a SQL query is also very important because if you don't, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!

No comments:

Post a Comment