基于foreach的动态SQL语句

时间:2018-06-25 17:51:36

标签: php mysql

由于现在我刚收到错误,我将如何使用它。

$_GET['providers'] is an array of DB column names, which I am checking if = 1 in the below query.

foreach ($_GET['providers'] as $providers) {
  $statement = "AND ".$providers."= '1' ";
}
$sql = "select * from users where user_id ='1' ".$statement." ";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
 echo "It worked";
}

2 个答案:

答案 0 :(得分:0)

您应该使用白名单来检查$providers是否为已知列名。然后,您应该串联$statement,否则在每次迭代时都覆盖该变量。

$statement = '';
$columns = array('known', 'columns', 'go', 'here');
foreach ($_GET['providers'] as $providers) {
    if(in_array($providers, $columns)) {
           $statement .= " AND $providers = 1 ";
    }
}
$sql = "select user_id from users where user_id =1 $statement limit 1";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
    echo "It worked";
}

除非您确实想要每列,否则也不应使用*。如果您只想查看是否返回了一行,则也可以使用limit 1,因为您并不关心其他行。

答案 1 :(得分:0)

每次循环运行时,您都将覆盖$ statement。

decimal="16" dataLoadedEvent="{{formatData}}"