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

穿精又带淫゛_ 提交于 2019-12-01 05:19:35

问题


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

<?php
$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));
?>

回答1:


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...




回答2:


First a few tips:

  1. Please read carefully the AdoDB documentation on prepared statements.
  2. Never include ; in SQL query strings.

You can try something like this:

$question_marks = substr(str_repeat('?,', count($first_names)), 0, -1);

$query = "SELECT mytable_id_pk FROM mytable WHERE mytable_fname IN (" . $question_marks . ")";
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt,$first_names);

WARNING: I haven't tested this (not having a mySQL installation here).



来源:https://stackoverflow.com/questions/10698524/parameterised-in-clause-in-prepared-statement-using-mysql-php-and-adodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!