【问题标题】:Searching every single word in different column within same table with a single query使用单个查询搜索同一表中不同列中的每个单词
【发布时间】:2015-06-08 03:00:24
【问题描述】:

我有一个string

$searchkey="a b c";

我有三列:

$column=array('column1','column2','column3');

我想检查这些列中的每个单词并获得一个查询字符串。为了得到它,我做了以下......但它看起来不像我想要的......我对 PHP 很陌生,所以我是堆栈。你能帮忙解决它或任何其他简单的方法来获取单个查询字符串!!!

$searchkey="a b c";
$words = EXPLODE(" ",$searchkey);
$column=array('column1','column2','column3');

foreach($column as $column){    
   for($i=0; $i<count($words); $i++){
       $string1.=''.$column.' like %'.$words[$i].'% or ';
   }
   $string1 = SUBSTR($string1,0,STRLEN($string1)-4);
   $string2.= '('.$string1.') or ';

}
echo $string2= SUBSTR($string2,0,STRLEN($string2)-4);

它给了我:

(column1 like %a% or column1 like %b% or column1 like %c%) or (column1 像 %a% 或 column1 像 %b% 或 column1 像 %c%column2 像 %a% 或 column2 like %b% or column2 like %c%) or (column1 like %a% or column1 像 %b% 或 column1 像 %c%column2 像 %a% 或 column2 像 %b% 或 column2 like %c%column3 like %a% or column3 like %b% or column3 like %c%)

但是,我想得到:

(column1 like %a% or column1 like %b% or column1 like %c%) or (column2 like %a% or column2 like %b% or column2 like %c%) 或 (column3 like %a% or column3 like %b% or column3 like %c%)

提前致谢。

【问题讨论】:

    标签: php arrays for-loop mysqli


    【解决方案1】:

    您只需将$string1 = ""; 语句添加为foreach 循环体中的第一条指令,以便在每次迭代中重置它,而不是每次都添加!


    ...
    foreach($column as $column) {
       $string1 = ""; // <-- Add this line, and every thing will be fine :)
       for($i=0; $i<count($words); $i++) {
           $string1.=''.$column.' like %'.$words[$i].'% or ';
       }
    ...
    

    【讨论】:

    • 原来我加了$string1='';和 $string2='';在 foreach 循环之前,现在我在 foreach 循环下面做了 $string1='' ,没有看到任何变化,除了一个错误说 undefined string1
    • 兄弟,你能不能用我的代码指出我需要改变的位置。
    猜你喜欢
    • 2017-01-08
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 2015-08-30
    • 1970-01-01
    相关资源
    最近更新 更多