PHP虽然命令缺少第一个条目

时间:2017-12-07 18:19:05

标签: php mysql while-loop phpmyadmin

我试图使用while循环从MySQL数据库打印多个条目。我做到这一点,它缺少列表中的第一个项目,只能设法从第二个项目打印。

<?php
require 'db.php';
$udate = $mysqli->escape_string($_POST['date']);
$result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");
$user = $result->fetch_assoc();
$_SESSION['file_name'] = $user['file_name'];
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>View</title>
        <link rel="stylesheet" type="text/css" href="css/nominatorstyle.css">  
    </head>
    <body>
        <div class="header">
            <h2>Results.</h2>
            <form action="watch.php" method='POST'><table>
                <?php 
                    if($result->num_rows > 0){
                        while($row = $result->fetch_assoc()){
                            $vid = $row['vid'];                           
                            $source = "uploads/".$row['file_name'];
                            echo "<tr><td>".$row['vid']."</td>
<td>".$row['file_name']."</td>";
                            echo "<td><a href=watch.php?
source=$source>Play</a></td></tr>";
                        }
                    }else{
                    echo "0 results";
                    } 
                ?>
                </table></form>
            <a href="profile.php"><button class="button-block">Home</button></a>
        </div>      
    </body>

我希望它能打印所有匹配的标准。 我只得到第一个之后的条目。

2 个答案:

答案 0 :(得分:0)

        require 'db.php';
        $udate = $mysqli->escape_string($_POST['date']);
        $result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");

        /*
         This fetch_assoc will get your first row #0 of the query
         next fetch_assoc with your loop on the $result 
         will start as you said from row #1
        */
        $user = $result->fetch_assoc(); //your missing row #0
        $_SESSION['file_name'] = $user['file_name'];

答案 1 :(得分:-1)

你错过了一个&#34;}&#34;在你的while循环结束时,这可能是个问题..我还将你的num_rows条件的&gt; = 1更改为&gt; 0.试试这个:

if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $vid = $row['vid'];                           
        $source = "uploads/" . $row['file_name'];
        $htmlRow  = "<tr>\n";
        $htmlRow .= "<td>" . $row['vid'] . "</td>\n";
        $htmlRow .= "<td>" . $row['file_name'] . "</td>\n";
        $htmlRow .= "<td>" . $row['vid'] . "</td>\n";
        $htmlRow .= "<td><a href=\"watch.php?source=" . $source . "\">Play</a></td>\n";
        $htmlRow .= "</tr>\n";
        echo $htmlRow;
    }
}