0

I have this code:

if (isset($_GET['id'])) { //$_GET['id'] = id=34,33,32,31
    $id = $_GET['id'];
}
try {
    $conexion = new conexion();
    $db = $conexion -> getConexion();
    $sql = "DELETE FROM `contactos` WHERE `id` IN (:id);";
    $q = $db -> prepare($sql);
    $q -> bindValue(':id',$id,PDO::PARAM_STR);
    $resultado = $q -> execute();
    if ($resultado){
       echo 'win';
    }else{
       echo 'fail';
    }

I use the parameter IN but it doesn't work in PDO with parameters. What can I do to send multiple values in one variable ?

  • You don't need a prepared statement for that, nor do you bind anything when using `IN` with an array of integers. If you were to use prepared statements, you'd prepare the statement **once**, then loop through your array of ID's and for each ID you'd bind + execute. – N.B. Jul 18 '18 at 15:01
  • Why I don't need use prepared statements ? – Marco Leslie Jul 18 '18 at 15:07
  • Why do you think you do need it? What does a prepared statement do for you in this case? What's the gain? – N.B. Jul 18 '18 at 15:17
  • >Why do you think you do need it? Maybe it's a stupid answer but... because is more secure? I'm new in this and I learn recently that prepared statements are more secure – Marco Leslie Jul 18 '18 at 15:23
  • No, it's not a stupid answer - you're almost correct. Basically, prepared statements do two things: they sanitize input and they help performance since they are lexed once, used multiple times. However, the `IN` operator expects a list. In your case, a list of integers. You can't bind that via prepared statements. Therefore, you either ensure all values in your `$_GET` are integers on your own or you don't use `IN` operator. The correct way would be to prepare a statement, loop the array, execute queries one by one. Wrap it in a transaction and you get a fast solution on top of it. – N.B. Jul 18 '18 at 16:29

0 Answers0