如何在SQL查询和PHP中匹配字符串中的单词并检索数据?
问题描述:
I have a MySql Table just like this
Brand
--------
Honda
Sozuki
Oddi
.
.
.
Now there is an dynamic array in PHP :
$brand = ["Sozuki","Honda"]
The Question is how to retrieve data that matches the word in above array. I tried this :
$qry = 'select * from brand where brand Like '% $brand[0] %' and '% $brand[1] %';
It works fine but what would I do if I have no specific length of array, you can say dynamic array. Any solution will be appreciated Thanks
我有一个像这样的MySql表 p>
Brand \ n --------
Honda
Sozuki
Oddi
。
。
。
code> pre>
现在PHP中有一个动态数组: p>
$ brand = [“Sozuki”,“Honda”]
code> pre>
问题是如何检索数据 与上面数组中的单词匹配。 我试过这个: p>
$ qry ='select * from brand brand brand'%$ brand [0]%'和'%$ brand [1]%'; \ n code> pre>
它工作正常但如果我没有特定长度的数组,我会怎么做,你可以说动态数组。
任何解决方案将不胜感激 p>
div>
答
try
$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;
答
You should define array as
$brand = array("Sozuki","Honda");
so then you can use $brand[0]
, etc ...
$qry = "SELECT * FROM brand WHERE brand LIKE '%{$brand[0]}%' AND '%{$brand[1])%'";
答
Wouldn't you rather use OR instead of AND?
If so use something like this (note: 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);
答
You could try:
$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 ';
}
}
答
<?php
$i=0;
$brand=array("Volvo","BMW","Toyota","Honda","Suzuki");
$qry = 'select * from brand where brand Like '% $brand[i] `enter code here`%'';
$i++;
?>