1

I am not sure where to put mysqli_real_escape_string() into my current PHP code for MySQL.

I have the URl http://www.example.com/abc-vs-def-vs-ghi/, but I know it can be exposed to http://www.example.com/abc:_?!$123-vs-1312+'.

My code is:

// This I got from my URL - be aware of SQLi!!!
$uri_segments="abc-vs-def-vs-ghi";

// array to get abc def ghi
$compare = explode('-vs-',$uri_segments[0]);

// db connection
$con = mysqli_connect("localhost","user","password","database");

// array for ID's by url segment abc, def, ghi for later
$device_models = array();

// loop array abc def ghi to get the ID from database
foreach ($compare as $model) {

// sql - where to put mysqli_real_escape_string()?
$sql = <<<SQL
SELECT model_id
FROM device_model
WHERE device_model.model_seo_url = '${model}'
SQL;

// get the id for abc, def, ghi
$result = mysqli_query($con, $sql) or die(mysqli_error($con));

  while($row = mysqli_fetch_assoc($result)){
    $device_model_id = $row['model_id'];
    // add id to array
    $device_models[] = $device_model_id;
  }

}

// close connection
mysqli_close($con);

// id 1,2,3
$var = implode (",", $device_models);
echo $var; // 1,2,3

Should i put int insie $sql variable, like 'mysqli_real_escape_string(${model})'?

Or '${mysqli_real_escape_string(model)}'?

I cannot get it work.

Maybe inside foreach() loop?

Thank you for help!

Kiki FIstrek Novi
  • 185
  • 1
  • 1
  • 11
  • 2
    The answer is to use prepared statements - https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Nigel Ren Dec 18 '18 at 07:04
  • Inside your ``foreach``: ``$escaped_model = mysqli_real_escape_string($model);`` Change your SQL statement to: ``WHERE device_model.model_seo_url = '${escaped_model}'`` – kmoser Dec 18 '18 at 07:16

0 Answers0