PHP-错字教程?

时间:2012-07-07 05:11:59

标签: php

I followed this phpacademy tutorial on youtube我无法通过echo打印关键字。 相反,我得到:

`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;
    }

?>

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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;
    }

?>

答案 2 :(得分:0)

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