Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing values to MySQL IN operation in PDO prepared statement?

Tags:

php

mysql

pdo

I have a form field that is returning a comma-delimited string that I want to pass in to a PHP PDO MySQL query IN operation, but the IN operation requires that the values be comma-delimited (as opposed to my string of delimited values).

How do I do this?

$values = $_POST['values']; # '10,5,4,3' (string)
$query = "SELECT * FROM table WHERE id IN (:values)";
$data = array( ':values' => $values );
like image 779
neezer Avatar asked Jan 20 '23 17:01

neezer


1 Answers

You can't pass in multiple values in a single placeholder. You will have to enter a different placeholder for each value to be passed into IN (). Since you don't know how many there will be, use ? instead of named parameters.

$values = explode(',', $values) ;

$placeholders = rtrim(str_repeat('?, ', count($values)), ', ') ;
$query = "SELECT * FROM table WHERE id IN ($placeholders)";

$stm = $db->prepare($query) ;
$stm->execute($values) ;
like image 144
Fanis Hatzidakis Avatar answered Apr 27 '23 06:04

Fanis Hatzidakis