I followed this phpacademy tutorial on youtube和我无法通过echo获取要打印的关键字。相反,我得到的是:
`keywords` LIKE '%keyword%'什么?代码已被逐字复制。可能是平台问题?
-> $where .= "keywordsLIKE '%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;
}
?>发布于 2012-07-07 13:23:45
我对你的代码做了一些重构,现在更清楚了。请参阅代码中的注释。
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);
}发布于 2012-07-07 13:20:22
当您看到以下代码时,
`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;
}
?>发布于 2012-07-07 13:38:09
在我看来,这只是where子句中教程中的一个拼写错误-在关键字变量名之前缺少$字符。其他答案已经提供了答案,但没有指出它看起来像是打字错误。对于来自其他语言的人来说,这是一个常见的打字错误,因为他们不需要像PHP那样在变量名前加上前缀。
https://stackoverflow.com/questions/11372437
复制相似问题