2012-07-07 82 views
0

I followed this phpacademy tutorial on youtube我无法获取通过echo打印的关键字。 而是我得到:PHP-错误的教程?

`keywords` LIKE '%keyword%' 

WTH?代码已被逐字复制。可能是平台问题?

这个说法有没有问题 - >$where .= "关键字LIKE '%keyword%'";

<?php 

    include 'db.inc.php'; 

    function search_results($keywords) { 
     $returned_results=array(); 
     $where=""; 

     $keywords=preg_split('/[\s]+/', $keywords); 
     $total_keywords = count($keywords); 

     foreach($keywords as $key=>$keyword){ 
      $where .= "`keywords` LIKE '%keyword%'"; // Where's the issue? 
      if($key != ($total_keywords-1)){ 
       $where .= " AND "; 
      } 
     } 

     echo $where; 
    } 

?> 
+1

你没有在任何地方使用'$关键字' - 这可能是问题吗? – andrewsi 2012-07-07 05:15:04

+3

你probaby想要'$其中。=“\'关键字\'LIKE'%$关键字'”;'见http://php.net/manual/en/language.types.string.php – 2012-07-07 05:15:34

回答

1

我对代码做了一些重构,现在更清楚了。请参阅代码中的注释。

include 'db.inc.php'; 

function search_results($keywords) { 
    $where = array(); 

    // skip empty results with PREG_SPLIT_NO_EMPTY flag 
    $keywords = preg_split('/[\s]+/', $keywords, -1, PREG_SPLIT_NO_EMPTY); 

    foreach ($keywords as $keyword) { 
     // escape string (anti sql injection) 
     $keyword = mysql_real_escape_string($keyword); 

     // your problem was using keyword instead of $keyword 
     $where[] = "`keywords` LIKE '%$keyword%'"; 
    } 

    echo implode(' AND ', $where); 
} 
0

当你看到下面的代码,

`keywords` LIKE '%keyword%' 

的教程,告诉您它,你需要用任何你想要的关键字替换%keyword%,两个%的之间。所以,你的代码应该看起来像这样:

<?php 

    include 'db.inc.php'; 

    function search_results($keywords) { 
     $returned_results=array(); 
     $where=""; 

     $keywords=preg_split('/[\s]+/', $keywords); 
     $total_keywords = count($keywords); 

     foreach($keywords as $key=>$keyword){ 
      $where .= "`keywords` LIKE '%$keyword%'"; // Issue fixed. 
      if($key != ($total_keywords-1)){ 
       $where .= " AND "; 
      } 
     } 

     echo $where; 
    } 

?> 
0

它在我看来只是从where子句中的教程中输入错误 - 在关键字变量名称前缺少$字符。其他答案提供了答案,但没有指出它看起来像一个错字。对于来自其他语言的人来说,这是一个常见的错字,不需要像PHP那样的变量名称的前缀。