如果多行符合条件,PHP仅显示MySQL数据

时间:2013-11-30 21:17:59

标签: php database mysqli

概览

所以,我正在研究一种“搜索脚本”,以帮助用户根据2种不同类型的数据查找数据。他们可以通过 Category 或从我的数据库中抓取的 Encoding 进行搜索。

问题:

数组只返回1行,而我的数据库中有3个(确切的)重复项,如果条目不同,问题仍然存在。

代码段:

<?php
$catagory = mysql_real_escape_string($_GET['c']);
$encode = mysql_real_escape_string($_GET['e']);
$query = "SELECT * FROM posts WHERE ";
if(!empty($catagory)) {
$query =$query . "catagory = '$catagory'" ;
}
if(!empty($encode)) {
    if(!empty($catagory)) {
        $query = $query . " AND " ;
    }
    $query = $query. "urlencode = '$encode'" ;
}

$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
if (empty($row)) {
    $message = "Sorry, there were no results";
    echo $message;
} ELSE {
    echo '<table>';
    echo '<thead>';
    echo '<th>Title</th><th>Posted</th><th>Address</th><th>Views</th>';
    echo '</thead>';
    echo '<tbody>';
    $now = date('Y-m-d H:i:s');
    while($row = mysqli_fetch_array($result)) {
        $title = htmlspecialchars($row['titlepre']);
        echo $row['titlepre'];
        $posted = dateDiff($row['date'],$now);
        $address = $row['address'];
        $views = $row['views'];
        $url = $row['url'];
        echo '<tr><td><a href ="'.$url.'">'.$title.'</a></td><td>'.$posted.'</td><td>'.$address.'</td><td>'.$views.'</td></tr>';
    }
    echo '</tbody>';
    echo '</table>';
}
?>

数据库信息

| ID | address  | title | titlepre | content |   Catagory     |  url  | urlencode | views |  date
--------------------------------------------------------------------------------------------------
| 3  |[WITHHELD]| title |  title   | content | Rants - Things | HDyLkl | Scheme   |   1   |2013-11-28 |
| 5  |[WITHHELD]| title |  title   | content | Rants - Things | HDyLkl | Scheme   |   1   |2013-11-28 |

现在,我对PHP很新,所以如果我的代码效率不高,请耐心等待。

1 个答案:

答案 0 :(得分:1)

每次使用* mysqli_fetch_array *都会从结果集中移出记录。

您已检查结果:

$row = mysqli_fetch_array($result);

因此 $ results 的第一条记录被“删除”。

do{
    $title = htmlspecialchars($row['titlepre']);
    echo $row['titlepre'];
    $posted = dateDiff($row['date'],$now);
    $address = $row['address'];
    $views = $row['views'];
    $url = $row['url'];
    echo '<tr><td><a href ="'.$url.'">'.$title.'</a></td><td>'.$posted.'</td><td>'.$address.'</td><td>'.$views.'</td></tr>';
}while($row = mysqli_fetch_array($result)) 

应该有效。

但转向PDO / mysqli目标。他们有一个迭代器。