Why should we escape double quotes,single quotes creating queries in PHP

1.6k views Asked by At

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?

3

There are 3 answers

3
flowfree On

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

2
Udit Trivedi On

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='[email protected]'";

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!

0
Jayabal On