eddy1992's avatar

Sql Injection

Hi, I have a project which is running an old version of PHP and MySQL. I am using queries like this

mysql_query("select * from user_favorites1 where users_id='$user_phone' AND products_id='$products_id' LIMIT 0,1");
$count=mysql_num_rows($ip_sql);

$sql_in = "insert into user_favorites1 (users_id,products_id,user_country_code,lastupdatetime,isAd) values ('$user_phone','$products_id','$user_country_code','$mss','$isAd')";
mysql_query($sql_in);
$result = array("status" => 0);
echo json_encode($result);

What will be the way to prevent SQL injection in the current code base rather than upgrading the whole code. Please assist.

0 likes
3 replies
36864's avatar

Using prepared statements would be a good first step.

$stmt = PDO::prepare("select * from user_favorites1 where users_id=:USER_PHONE AND products_id=:PRODUCT_ID LIMIT 0,1");
$stmt->bindValue(':USER_PHONE', $user_phone);
$stmt->bindValue(':PRODUCT_ID', $products_id);
$stmt->execute();
$result = $stmt->fetchAll();    

Failing that, lots and lots of input sanitization.

jlrdw's avatar

Go with pdo, far better. Laravel uses pdo. @36864 that was a nice example you gave. You can even write regular PDO queries in laravel Using getPdo(). Look under the guides topic, I posted an example.

Edit: I was on mobile earlier, here are quick examples of getPdo: https://laracasts.com/discuss/channels/guides/getpdo-usage

An application using PDO could be ported to laravel in a short time. And even if you wanted to convert some things to eloquent or query builder, the app could still be used while some re-coding is taking place in a development app.

Please or to participate in this conversation.