基本Php / Mysql搜索:rowCount()返回错误

时间:2014-01-02 18:23:02

标签: php

我正在开发一个非常基本的php / mysql搜索。搜索基于下拉菜单中选择的值的过滤条件。有三个选项Whole SitePagesBlogs。在我的PHP代码中,我准备sql语句,然后相应地执行所选的过滤器。我在$count = $query->rowCount()收到错误,但最有趣的是当我尝试回显查询结果时我得到1。如何显示正确的值并克服错误? DEMO

PHP / Mysql

<?php
require("db_con/db_con.php");
$search_output = "";
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
  $searchquery = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['searchquery']);
  if($_POST['filter1'] == "Whole Site"){
    $sqlCommand = $db_con->prepare("(SELECT id, page_title AS title FROM pages WHERE MATCH (page_title,page_body) AGAINST ('$searchquery')) UNION (SELECT id, blog_title AS title FROM blog WHERE MATCH (blog_title,blog_body) AGAINST ('$searchquery'))");
  } else if($_POST['filter1'] == "Pages"){
    $sqlCommand = $db_con->prepare("SELECT id, page_title AS title FROM pages WHERE MATCH (page_title,page_body) AGAINST ('$searchquery')");
  } else if($_POST['filter1'] == "Blog"){
    $sqlCommand = $db_con->prepare("SELECT id, blog_title AS title FROM blog WHERE MATCH (blog_title,blog_body) AGAINST ('$searchquery')");
  }

    $query = $sqlCommand->execute();
    $count = $query->rowCount();
  if($count > 1){
    $search_output .= "<hr />$count results for <strong>$searchquery</strong><hr />$sqlCommand<hr />";
    $query->fetchAll();
       foreach($row as $query){
         $id = $row["id"];
         $title = $row["title"];
         $search_output .= "Item ID: $id - $title<br />";
        } // close while
  } else {
    $search_output = "<hr />0 results for <strong>$searchquery</strong><hr />$sqlCommand";
  }
}
?>

HTML

<h2>Search the Exercise Tables</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Search For:
  <input name="searchquery" type="text" size="44" maxlength="88">
Within:
<select name="filter1">
<option value="Whole Site">Whole Site</option>
<option value="Pages">Pages</option>
<option value="Blog">Blog</option>
</select>
<input name="myBtn" type="submit">
<br />
</form>
<div>
<?php echo $search_output; ?>

2 个答案:

答案 0 :(得分:1)

rowCount()函数仅返回受DELETE,INSERT或UPDATE语句影响的行数。要获取SELECT语句的行数,您必须执行单独的查询,如下所示:

<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {

  /* Check the number of rows that match the SELECT statement */
  if ($res->fetchColumn() > 0) {

         /* Issue the real SELECT statement and work with the results */
         $sql = "SELECT name FROM fruit WHERE calories > 100";
         foreach ($conn->query($sql) as $row) {
           print "Name: " .  $row['NAME'] . "\n";
         }
    } else { /* No rows matched -- do something else */
      print "No rows matched the query.";
    }
}

$res = null;
$conn = null;
?>

这是来自PHP手册,这里: http://ca2.php.net/manual/en/pdostatement.rowcount.php

答案 1 :(得分:-2)

尝试使用$fetchColumn代替$rowCount