根据数组内容创建mysqli查询参数

时间:2015-06-12 15:29:30

标签: php

我正在尝试使用LIKE运算符构建查询:

$args = array("this", "that", "other");

$query = $db->query("SELECT * FROM tblStockDet WHERE StockMastID LIKE '%{$args[0]}%'");

这样可以只返回tblStockDet包含术语“this”的结果。但是,我可能在数组中有几个LIKE个参数。因此,在上面的示例中,$args数组有3个值。如何自动更新查询,如下所示:

$query = $db->query("SELECT * FROM tblStockDet WHERE StockMastID LIKE '%{$args[0]}%' AND StockMastID LIKE '%{$args[1]}%' AND StockMastID LIKE '%{$args[2]}%'");

1 个答案:

答案 0 :(得分:0)

一种方法可能是尝试foreach

$args = array("this", "that", "other");
$stmt = array('0'); // Prevent errors when $args is empty

foreach ($args as $arg) {
    $stmt[] = 'StockMastID LIKE %'.$arg.'%';
}

$query = $db->query("SELECT * FROM tblStockDet WHERE ".implode(" AND ", $stmt));