MySQL函数给出错误的值

时间:2015-11-10 08:22:12

标签: php mysql

我正在创建一个搜索引擎,我需要根据输入的关键字显示视频。

所以对于我的代码,我有

$search_exploded = explode (" ", $search);
            foreach($search_exploded as $search_each){
                $x = 0; 
                $x++;

                if($x>=1){
                    $construct ="keywords LIKE '%$search_each%'";
                }

                else{
                    $construct ="OR keywords LIKE '%$search_each%'";

                }
                $x = 0;
            }

$query ="SELECT * FROM test WHERE $construct";

                    $runquery = mysql_query($query);

                    $foundnum = mysql_num_rows($runquery);

问题在于$ runquery,因为我从浏览器得到的错误表明行$foundnum = mysql_num_rows($runquery);返回的是布尔值而不是假设的资源类型值。

有人可以帮忙解决这个问题吗?我已经坚持了很长一段时间了。感谢并感谢任何帮助!

4 个答案:

答案 0 :(得分:2)

如果条件和每次将$ x设置为0都存在问题,那么为什么要启动它。

   $x = 0;
  foreach($search_exploded as $search_each){               
           if($x==0){ 
                $construct =" keywords LIKE '%$search_each%' ";
            }else{
                $construct .=" OR keywords LIKE '%$search_each%' ";
            }
            $x++;
        }

试试这个。

答案 1 :(得分:2)

您的foreach循环中有一些与$x变量相关的逻辑错误。

这是一种实现您想要做的事情的简单方法(不使用$x之类的某种标志) -

$search_exploded = explode (" ", $search);

// An array for the `LIKE` conditions
$construct_list = [];

// Adding the conditions in the array
foreach($search_exploded as $search_each){
    $construct_list[] = "keywords LIKE '%$search_each%'";
}

// Joining them using OR
$construct = implode(" OR ", $construct_list);

// Supposing there are no keywords, the
// WHERE should not exist. So make a separate var for that - 
$where_clause = "";
if(trim($construct) != ""){
    $where_clause = "WHERE $construct";
}

// Perform your query
$query ="SELECT * FROM test $where_clause";

答案 2 :(得分:0)

试试这个:

            $search_exploded = explode (" ", $search);
            $construct = '1';
            if (!empty($search_exploded)) {
                $construct = '';
                foreach($search_exploded as $search_each){
                    $construct .= $construct == '' ? " keywords LIKE '%$search_each%'" : " OR keywords LIKE '%$search_each%'";
                }
            }
            $query ="SELECT * FROM test WHERE $construct";

            $runquery = mysql_query($query);
            if ($runquery) {
                $foundnum = mysql_num_rows($runquery);
            }

答案 3 :(得分:0)

你似乎试图省略围绕循环的第二次和后续运行的OR,但保留第一次。应该是相反的方式,。

但我可能会避免使用循环,只使用implode。像这样的东西(虽然在查询中使用它们之前需要转义值)。

$search_exploded = explode (" ", $search);

if (count($search_exploded) > 0)
{

    $construct = implode("%' OR keywords LIKE '%", $search_exploded);

    $query ="SELECT * FROM test WHERE keywords LIKE '%".$construct."%'";

    $runquery = mysql_query($query);

    $foundnum = mysql_num_rows($runquery);

}