-1

Below codes is taken from one tutorial:

 <?php
// user input that uses SQL Injection
$name_bad = "' OR 1'"; 

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

// display what the new query will look like, with injection
echo "Injection: " . $query_bad;

In front end, it shows:

Injection: SELECT * FROM customers WHERE username = '' OR 1''

Question:

why it shows username = '' OR 1''?

user2507818
  • 2,719
  • 5
  • 21
  • 30
  • @David — No, don't. The `mysql_*` library is deprecated and shouldn't be used at all and [there are better ways to protect against SQL injection](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) than escaping. – Quentin Jul 29 '13 at 08:42

5 Answers5

1

PHP strings quoted with " characters interpolate variables and treat ' characters as literals.

$name_bar is a string that contains ' characters.

When it is interpolated, all the characters in it are placed where the variable was.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

In PHP if in double quotes you write any variable it is replace by value of the variable as perfectly done by PHP in your case

// user input that uses SQL Injection
$name_bad = "' OR 1'"; 

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

if I replace the value $name_bad with ' OR 1' then it would become

SELECT * FROM customers WHERE username = '' OR 1'';

and if you want to remove the extra ' before and after your query then you have write your query as:

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = $name_bad";
Vineet1982
  • 7,730
  • 4
  • 32
  • 67
1

Because you're basically just concatting the strings.

$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

is the same as

$query_bad = "SELECT * FROM customers WHERE username = '' OR 1''";

since $name_bad is ' OR 1'.

h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
1

It does that because $name_bad includes the single quotes, and you have inserted it between another set of quotes in the other string.

For best practice, use:

$string = sprintf('SELECT * FROM customers WHERE username = \'%s\'', ' OR 1');

On to the SQL however, it will need to be sanitized.

If you are using PDO, the bindParam method will automatically prevent SQL injection (it states).

http://www.php.net/manual/en/pdo.prepared-statements.php

Flosculus
  • 6,880
  • 3
  • 18
  • 42
1

See explanation in this image:

enter image description here