提问人:Timothy 提问时间:10/25/2022 最后编辑:user3783243Timothy 更新时间:10/26/2022 访问量:453
如何通过匹配存储在表列中的字符串中的单个单词来查找数据库中的数据
how to find data from database by matching single word in a string stored in table's column
问:
这是从表中查找地址的查询,其中它与变量 ,$fromCity
$fromCity= "324 West Gore Street, Orlando, FL 32806, USA";
$sql = "SELECT * FROM vendor_info WHERE mailing_address LIKE '$fromCity'";
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$company = $stmt->fetchAll();
dd($company);
在表中,列如下所示vendor_info
mailing address
324 WEST GORE STREETORLANDO, FL 32806
如果任何一个单词与列匹配,我想得到结果mailing_address
现在的结果是空数组,dd(company);
请帮我找出这个解决方案,它是在symfony中,
答:
1赞
mscdeveloper
10/26/2022
#1
也许是这样的:
$fromCity = "324 West Gore Street, Orlando, FL 32806"; $fromCity_arr = explode(', ', $fromCity); $whereStr = ''; foreach($fromCity_arr as $fromCity_el){ if(!empty($whereStr)){$whereStr .= " AND ";} $whereStr .= "mailing_address LIKE '%".$fromCity_el."%'"; } $sql = "SELECT * FROM vendor_info WHERE $whereStr"; ......
结果:
SELECT * FROM vendor_info WHERE mailing_address LIKE '%324 West Gore Street%' AND mailing_address LIKE '%Orlando%' AND mailing_address LIKE '%FL 32806%'
评论
0赞
Rufinus
10/26/2022
$fromCity = "%';--"
0赞
Rufinus
10/26/2022
#2
@mscdeveloper 的答案基本上是正确的 - 但是当您使用 doctrine 时,您还应该使用准备好的语句来避免 SQL 注入。
$fromCity = "324 West Gore Street, Orlando, FL 32806";
$fromCity_arr = explode(', ', $fromCity);
$stm = $this->getEntityManager()->getRepository(MyModel::class)->getQueryBuilder('a');
for($i=0;$i<count($fromCity_arr);$i++) {
$stm->andWhere('a.mailing_address like ?)
->setParameter($i+1, '%'.$fromCity_arr[$i].'%');
}
$result = $stm->getQuery()->getResult();
dump($stm->getQuery()->getSql());
dd($result);
评论
'%$fromCity%'
like
or
USA
if any single word is match
street