我有一个像这样的MySql表
Brand
--------
Honda
Sozuki
Oddi
.
.
.
现在PHP中有一个动态数组:
$brand = ["Sozuki","Honda"]
问题是如何检索与上面数组中的单词匹配的数据。我试过这个:
$qry = 'select * from brand where brand Like '% $brand[0] %' and '% $brand[1] %';
它工作正常但如果我没有特定长度的数组,我会怎么做,你可以说动态数组。 任何解决方案将不胜感激
答案 0 :(得分:4)
你宁愿使用OR代替AND吗?
如果是这样,请使用类似的内容(注意: UNTESTED ):
<?php
$brands = array(1, 2, 3, 7, 8, 9);
$inQuery = implode(',', array_fill(0, count($brands), '?'));
$db = new PDO(...);
$stmt = $db->prepare(
'SELECT *
FROM brand
WHERE brand IN(' . $inQuery . ')'
);
foreach ($brands as $k => $brand)
$stmt->bindValue(($k+1), $brand);
$stmt->execute();
// Or simply $stmt->execute($brands);
答案 1 :(得分:0)
你可以尝试:
$qry = 'select * from brand where brand Like ';
for ($i = 0; $i < sizeof($brands)-1; $i++) {
$qry .= "'%" . $brand[$i] . "%'";
if ($i < sizeof($brands) - 2) {
$qry .= ' AND ';
}
}
答案 2 :(得分:0)
尝试
$qry = "select * from brand where brand ";
$i=1;
$count = count($brand);
foreach($brand as $v) {
$a = ($i < $count ? 'and' : '');
$qry .= " Like '% $v %' $a ";
$i++;
}
echo $qry;
答案 3 :(得分:0)
<?php
$i=0;
$brand=array("Volvo","BMW","Toyota","Honda","Suzuki");
$qry = 'select * from brand where brand Like '% $brand[i] `enter code here`%'';
$i++;
?>
答案 4 :(得分:-1)
您应该将数组定义为
$brand = array("Sozuki","Honda");
所以你可以使用$brand[0]
等......
$qry = "SELECT * FROM brand WHERE brand LIKE '%{$brand[0]}%' AND '%{$brand[1])%'";