PHP sql语句where子句为多个数组值

时间:2017-06-09 07:32:10

标签: php mysql sql arrays pdo

如果值[3]存储了多个数据,我如何使用数组的where子句

$fsql="select * from Error where RptDatime = 201706091000 and partnumber like  ('$value[3]')";
$getResults = $conn->prepare($fsql);        
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);    

foreach($results as $row)
{         
    $mac = $row['Machine'];                
    $id = $row['Id'];                
    echo 'ID:'.$id.'Machine Number :'.$mac;
}

2 个答案:

答案 0 :(得分:0)

您可以使用正则表达式而不是喜欢。以下是您的示例代码。

$partnumner = [];

    foreach($value[3] as $v)
    {
        $partnumber[] = "*.".$v.".*";
    }

    $fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP  '".implode("|",$partnumber)."'";

如果您仍希望使用,请按照here

的说明进行操作

答案 1 :(得分:-1)

我假设您有数组,所以首先应该验证预期的数据,然后将其内嵌到逗号分隔的字符串中。

if(!isset($value[3])){
    return false;
}
if(!is_array($value[3])){
    return false;
}
foreach($value[3] as $number){
    if(!is_numeric($number)){
        return false;
    }
}
$numbers = implode(",",$value[3]);
$fsql=sprintf("select * from Error where RptDatime = 201706091000 and partnumber in  (%s)",$numbers);
$getResults = $conn->prepare($fsql);        
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);    

foreach($results as $row)
{         
    $mac = $row['Machine'];                
    $id = $row['Id'];                
    echo 'ID:'.$id.'Machine Number :'.$mac;
}