Why should we escape double quotes,single quotes creating queries in PHP
Why should we escape double quotes,single quotes creating queries in PHP? are there any particular benefits when doing that? or it is just a good practice?
It is required to make your queries work and secure. Consider the following code:
$name = "O'reilly"; $sql = "INSERT INTO users (name) VALUES ('$name')";
The result SQL would become like this:
INSERT INTO users (name) VALUES('O'reilly');
Which simply doesn't work. It needs to be properly escaped:
INSERT INTO users (name) VALUES('O\'reilly');
The same applies for other special chars.
Prevent SQL injection
Consider this query:
DELETE FROM users WHERE username='$username';
Where $username is obtained from $_POST. If an attacker managed to post string like ' OR 1; -- as the $username then the query becoming this:
DELETE FROM users WHERE username='' OR 1; -- ';
which is valid and the WHERE always evaluates to true and you will have to give good explanation to your angry users.
See also: Best way to prevent SQL Injection in PHP
If you do not escape quotes, The query ends at the place of single quotes. So your query will not be executed successfully!
$qry = "SELECT * FROM user WHERE firstname.lastname@example.org'";
It works fine but if any one enters email@example.com' then query ends at 'test' only and not find any rows with that one.
So it prevents also a sql injection!
s, to prevent from SQL injection attacks. To know SQL injection http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php http://www.homeandlearn.co.uk/php/php13p5.html
To prevent PHP Sql injection https://stackoverflow.com/a/60496/781181