Tuesday, July 30, 2019

Parameterised IN Clause in prepared statement using MySql,PHP and ADODB




I am writing some SQL and using AdoDb to connect to my database and run the queries and so on. I am using parametrized queries and have run into a snag.



Is their a way to pass an array of values to an in_clause in AdoDb/MySql for parametrization.



My problem is that if I pass a prepared string as the parameter i.e. 'test','test2','test3' it does not work as the library or database auto escapes it and adds external quotes at the start and end so all the internal quotes are then auto escaped thus the query returns nothing as it looks for '\'test\',\'test2\',\'test3\'' as opposed to what I fed it.



UPDATED WITH ANOTHER POSSIBLE METHOD TO ACCOMPLISH THIS




$in_clause = implode(",", $first_names);

$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
FIND_IN_SET(mytable_fname," . $DB->Param('first_names') . ")"


$stmt = $DB->Prepare($query);

$result = $DB->Execute($stmt,array($in_clause));
?>

Answer



I would do it this way (as I was googling for a while and google came up with nothing useful):



$count = count($first_names);
$in_params = trim(str_repeat('?, ', $count), ', ');


$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
mytable_fname IN ({$in_params});";

$stmt = $DB->Prepare($query);

$result = $DB->Execute($stmt, $first_names);


This should do it...


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...