【问题标题】:search all the elements of array of strings in mysql using php使用php在mysql中搜索字符串数组的所有元素
【发布时间】:2014-02-27 08:59:57
【问题描述】:

我需要搜索数据库字符串数组的所有元素,并返回有多少值与现有数据库条目匹配..

database name = words , table name=collection , word 是要搜索的数组所在的列

<?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();
?>

【问题讨论】:

  • 应该是单词 LIKE '%".addslashes($s)."%'"
  • SELECT 查询不会更新受影响的行计数器。
  • @Andrew addslashes() 不适合 SQL 转义。
  • 顺便说一句,如果数组不是太大,您可以生成一个查询,它会一次性给您答案,即WHERE word LIKE ? OR word LIKE ? OR ...

标签: php mysql arrays


【解决方案1】:
$result = 0;
foreach($array as $s) {
    $query="select count(*) as number_match from collection where word = '%".$s."%'";
    $row = mysql_fetch_row($db->query($query));
    $result+= $row['number_match'];
}

编辑: 更好:

$words = implode("%','%",$array);
$query="select count(*) as number_match from collection where word in ('%$words%')";
var_dump(mysql_fetch_row($db->query($query));

【讨论】:

    【解决方案2】:
    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; 
       }
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      相关资源
      最近更新 更多