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?

Answers


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!

E.g.

$qry = "SELECT * FROM user WHERE email='test@test.com'";

It works fine but if any one enters email='test'@test.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


Need Your Help

Asp master page change content

asp.net

I am new to ASP and this question will be very basic.I searched the net for quite a while and I am starting to think that I'm trying to do something wrong.I have a very simple master page with 3

Put an applet in eclipse

java eclipse xhtml applet

I have made an applet in eclipse, and I can run it succesfully with right click on the java file and run as -> Java Applet