在PHP的WHERE子句中使用Array作为参数

时间:2018-03-10 18:43:03

标签: php

我想从我的workloaddata表中选择所有,其中Sched_Days字段至少有一天类似。用户选择的天数(通过复选框)。哪些值存储在$ wwdays变量中。

我通过$ daysIn = explode(',',$ wwdays,-1)将我的$ wwday转换为数组;

现在,我在$ WHERE子句中使用$ daysIn作为参数,但是我的查询返回了错误的结果。我的语法有问题吗?

 /*
 $wwdays has this string value "Monday, Tuesday, Wednesday, Saturday,"
 
 I've used $daysIn = explode(',', $wwdays, -1); To get just the days
 
 And used print_r($daysIn); to check the details, I have this result
 
 Array ( [0] => Monday [1] => Tuesday [2] => Wednesday [3] => Saturday ) 
 
 So I assume that my $daysIn variable is an array with the days as its element.
 
 */
 
$daysIn = explode(',', $wwdays, -1);

$connect = mysqli_connect("localhost", "root", "", "smis"); 
$sql = "SELECT * FROM workloaddata
WHERE Sched_Days IN (".implode(',',$daysIn).")
 ";
 $result = mysqli_query($connect, $sql);
 while($row = mysqli_fetch_array($result))  
{
// do things ..
}

// I'm having  mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\

1 个答案:

答案 0 :(得分:0)

你必须做类似下面的事情(注意评论):

// Connect to DB
$connect = mysqli_connect("localhost", "root", "", "smis");

$daysIn = explode(',', $wwdays);

// Clear white-spaces and prevent sql injection
$daysIn = array_map(function($item) use ($connect) {
    return mysqli_real_escape_string($connect, trim($item));
}, $daysIn);

// Remove empty items
$daysIn = array_filter($daysIn);

if (!empty($daysIn)) {
    // Wrap "" on condition values
    $sql = 'SELECT * FROM `workloaddata` WHERE `Sched_Days` IN ("'.implode('","',$daysIn).'") ';

    $result = mysqli_query($connect, $sql);
    while($row = mysqli_fetch_array($result))  
    {
        // do things ..
    }
}

但建议使用PDO 绑定参数,而不是直接进行查询。