使用php搜索mysql中字符串数组的所有元素
我需要搜索数据库字符串数组的所有元素,并返回与现有数据库条目匹配的值的数量 数据库名=单词,表名=集合,单词是要搜索的数组所在的列使用php搜索mysql中字符串数组的所有元素,php,mysql,arrays,Php,Mysql,Arrays,我需要搜索数据库字符串数组的所有元素,并返回与现有数据库条目匹配的值的数量 数据库名=单词,表名=集合,单词是要搜索的数组所在的列 <?php $array=array('abc','xyz','lmn','pqr'); @ $db=new mysqli('localhost','root','','words'); if(mysqli_connect_errno()) { echo 'Error:Could not connect to the database'; } els
<?php
$array=array('abc','xyz','lmn','pqr');
@ $db=new mysqli('localhost','root','','words');
if(mysqli_connect_errno()) {
echo 'Error:Could not connect to the database';
} else echo 'connected';
$db->select_db('words');
foreach($array as $s) {
$query="select * from collection where word = '%".$s."%'";
$result=$db->query($query);
}
if($result) echo $db->affected_rows;
$db->close();
?>
编辑:
更好的是:
$words = implode("%','%",$array);
$query="select count(*) as number_match from collection where word in ('%$words%')";
var_dump(mysql_fetch_row($db->query($query));
它应该是单词“%”的位置。addslashes($s)。“%”选择查询不会更新受影响的行计数器。@Andrewaddslashes()
不是用于SQL转义的。顺便说一句,如果数组不是太大,您可以生成一个查询,一次就可以给出答案,即where-word-LIKE?或word-LIKE?或…
$words = implode("%','%",$array);
$query="select count(*) as number_match from collection where word in ('%$words%')";
var_dump(mysql_fetch_row($db->query($query));
its not feasible to run query in for loop so, you can try below solution,
$array=array('abc','xyz','lmn','pqr');
$query="select word from collection where word LIKE '%".$s."%'";
$result=$db->query($query);
while ( $row = mysql_fetch_array($result) )
{
$tblarray[] = $row['word'];
}
foreach($tblarray as $k => $v)
{
foreach($array AS $key => $value)
{
if (strpos($v, $value) !== false)
{
$finalarray[] = $v;
}
}
}