Hello Friends,
If you are beginner in PHP and MySql OR you are not aware with SQL Injection while executing MySql Queries from PHP Code than you must know how to prevent SQL Injection in PHP. It is very important to take care of SQL Injection in your PHP code if you really cares for your client and his/her website security. Here I am sharing with you how to prevent SQL Injection in PHP.
You have 3 ways to prevent SQL Injection in your PHP code.
Using PDO
$sql_q = $pdo->prepare('SELECT * FROM tablename WHERE v_name = :v_name'); $sql_q->execute(array('v_name' => $v_name)); foreach ($sql_q as $single_row) { // do something with $single_row }
Using MySqli
$sql_q = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $sql_q->bind_param('s', $name); $sql_q->execute(); $res_arr = $sql_q->get_result(); while ($single_row = $res_arr->fetch_assoc()) { // do something with $single_row }
Using mysql_real_escape_string
$v_name = $_POST["v_name"]; $v_name = mysql_real_escape_string($v_name); mysql_query("INSERT INTO tablename (v_name) VALUES ('" . $v_name . "')");
Note : mysql_real_escape_string is deprecated as of PHP 5.5.0, and will be removed in the future. So please follow either first or second way to prevent SQL Injection.