sql Injection in php

sql Injection in php

SQL injection means to act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.
SQL Injection Example
<?php
// a good user's name
$name = "test";
$query = "SELECT * FROM customers WHERE username = '$name'";
echo "Normal: " . $query . "<br />";
// user input that uses SQL Injection
$name_dul = "' OR 1'";
// our MySQL query builder, however, not a very safe one
$query_dul = "SELECT * FROM customers WHERE username = '$name_dul'";
// display what the new query will look like, with injection echo "Injection: " . $query_dul; 

?> 
it will display query
Normal: SELECT * FROM customers WHERE username = 'test'
Injection: SELECT * FROM customers WHERE username = '' OR 1''
How can Prevent SQL Injection

Lucky for you, this problem has been known for a while and PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function mysql_real_escape_string

<?php
 //NOTE: you must be connected to the database to use this function! // connect to MySQL
$name_bad = "' OR 1'";
$name_bad = mysql_real_escape_string($name_bad);
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
echo "Escaped Bad Injection: <br />" . $query_bad . "<br />";
$name_evil = "';
DELETE FROM customers WHERE 1 or username = '";
$name_evil = mysql_real_escape_string($name_evil);
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
echo "Escaped Evil Injection: <br />" . $query_evil;
?>
it will display query

Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\' OR 1\''
Escaped Evil Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''