Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this safe enough for SQL injection

I just read about SQL injection and found this function on the blog i was reading I am wondering if it is safe for SQL injection.. say if i pass do remove_mq($_POST) to it, could i be using $_POST["var"] inside a query without a problem?

function remove_mq($array){
    foreach($array as $key => $value){
        if(is_array($value)){
            $array[$key] = remove_mq($value);
        }
        else{
            $array[$key] = addslashes($value);
        }
    }
    return $array;
}
like image 959
Dany Khalife Avatar asked Dec 30 '25 13:12

Dany Khalife


2 Answers

No. Addslashes is not the proper function to escape for a query. You need to use mysql_real_escape_string

Besides that, you should not perform SQL escaping before actually using a value in a query. Assume you have something like <input name="foo" value="$_POST[foo]" - then you need it htmlspecialchars()-escaped and not addslashes(etc.)-escaped


Besides that, the best solution would be using PDO with prepared statements since you separate SQL queries from params so you do not need any escaping at all.

like image 135
ThiefMaster Avatar answered Jan 02 '26 04:01

ThiefMaster


Best practice nowadays is prepared queries. Example:

$stmt = $pdo->prepare('SELECT username FROM users WHERE id = :id');
$stmt->execute(array(':id' => $_GET['id']));
$result = $stmt->fetchAll();

This code is totally secure

like image 42
Nanocom Avatar answered Jan 02 '26 03:01

Nanocom