-1

I generate a mysql query via $_GET in PHP via concatenation assignment (.=). take a look:

$sql='SELECT * FROM table WHERE ';
$sql.='ID='.$_GET['id'].'';
$query=$PDO->prepare($sql);

how can i prevent mysql injection? i use bind values for direct queries but in this case,i don't have any idea how i should write my code to be safe enough. note that i use PHP 7 and i can't use mysql_real_escape_string(); as it's not available in PHP7.

  • Loop over the `$_GET` and put a placeholder in for each value, then bind the values. Current example should be `$sql='SELECT * FROM table WHERE ID = ?';` then do prepare as you have and `$query->execute(array($_GET['id']));` – user3783243 Aug 13 '18 at 15:40
  • `$sql.='ID=?';` then `$query->bind_param('i', $_GET['id']);` – AbraCadaver Aug 13 '18 at 15:56

1 Answers1

1

You could use something like the following:

<?php
$sql = $PDO->prepare("SELECT * FROM table WHERE ID=?");
if ($sql->execute(array($_GET['id']))) {
  while ($row = $sql->fetch()) {
    print_r($row);
  }
}
?>
Evan Edwards
  • 182
  • 11