sql pdo php where in variable

こ雲淡風輕ζ 提交于 2021-02-11 18:08:11

问题


I'd like to select some data from my database using variables.

Here is a short version of my code:

// $a is either null or something like [1, 2]
if ($a) {
    $debug = implode(',', $a);
} else {
    $debug = [0-9];
}

$sql = "SELECT id FROM user WHERE id IN ($debug)"

How can I achieve that I get only user 1 and 2 (= value in $a) if $a is set and all user if $a is not set?


回答1:


First:
be aware when you directly inject string inside queries, because you can be target of a SQL Injection

Second:
change directly the query might be the easiest solution

// $a is either null or something like [1, 2]
$sql = "SELECT id FROM user";
if ($a) {
    $debug = implode(',', $a);
    $sql = "SELECT id FROM user WHERE id IN ($debug)";
}



回答2:


you can set flag on $a to check if its null $debug must contain a comma separated string with ids i.e '2,32,12,54,56,76'

$sql = "SELECT id FROM user ";
if(!empty($a)){
$debug = implode(',', $a); //here you must get string like '1,2,3,4,5'
$sql .= " WHERE id IN ($debug)";
}

//here if $a is empty you have all rows and if $a have values you get selected rows

//final query will be
// if a is empty 'SELECT id FROM user '
// else 'SELECT id FROM user WHERE id IN (1,2,3)' // where 1,2,3 got from $debug



来源:https://stackoverflow.com/questions/63039171/sql-pdo-php-where-in-variable

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