选择带有where子句的语句Like in array

时间:2017-09-26 18:29:47

标签: php sql pdo sql-like

我知道如何对单个值执行SQL LIKE%查询,如下所示:

$sql = "SELECT * FROM Farmers WHERE Available_products LIKE ('%Bananas%')";

但是如果我的LIKE的搜索条件来自数组,我该怎么做呢?例如,我们假设我们有一个这样的数组:

$_POST['Products']="Cacaos,Bananas";
$array=implode(',', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE Available_products LIKE ('%$array%')";

我想获取数据库中Available_Products列包含Cacaos或Bananas或Both

的所有记录

3 个答案:

答案 0 :(得分:1)

将数组转换为正则表达式,并使用REGEX代替LIKE

$_POST['Products'] = array('Cacaos', 'Bananas');
$regex = implode('|', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE Available_products REGEX :regex";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':regex', $regex);
$stmt->execute();

答案 1 :(得分:0)

您可以在REGEXP的帮助下尝试。

 $_POST['Products']="Cacaos,Bananas";
 $array=implode('|', $_POST['Products']); 
 $sql = "SELECT * FROM Farmers WHERE   
              Available_products REGEXP". $array; 

答案 2 :(得分:0)

您还可以执行以下操作:

// Populating join table.    
CREATE TABLE temp_table_myArray (myArray nvarchar(255));
    INSERT INTO temp_table_myArray (myArray) VALUES ('Cacaos');
    INSERT INTO temp_table_myArray (myArray) VALUES ('Bananas');

// Query using the join table.
    SELECT F.*
    FROM Farmers AS F
        INNER JOIN temp_table_myArray AS T ON (F.Available_products LIKE(CONCAT('%',T.myArray,'%')));

但我认为有更好的PHP方法可以解决您的问题......