|
Raakesh
|
 |
« on: October 21, 2008, 04:30:34 PM » |
|
There are so many inbuilt functions that PHP has for avoiding SQL injections but one way or the other, those intentional single quotes, double quotes, apostrophes, etc do bring up an error or two, occasionally. Here are some examples of how to avoid these errors.
Before you execute a mysql query make sure that each variable that you are going to submit to the db is verified that it doesn't have any mysql statements that can damage your system.
example - you have a contact us form that stores the information of the user on the db. $name=$_POST['name']; $phone=$_POST['phone']; $email=$_POST['email']; $comment=$_POST['comment'];
to make your code safe you can do any of the following: $name=addslashes($name); $phone=addslashes($phone); $email=addslashes($email); $comment=addslashes($comment); This will add a slash \ before each element like single quote ('), double quote ("), backslash (\) and NUL (the NULL byte). The primary purpose for this function is to avoid data entry errors as these could result in making your queries invalid (a comma will add a new field and result in mismatch of the number of fields you are inputing, etc.)
But using addslashes() is definitely not safest way out there. I highly recommend using mysql_real_escape_string() function: $name=mysql_real_escape_string($name); $phone=mysql_real_escape_string($phone); $email=mysql_real_escape_string($email); $comment=mysql_real_escape_string($comment); mysql_real_escape_string() calls the library function mysql_real_escape_string, that adds backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
This function should always be used to make your input data safe before the MySQL query is executed.
|