使用PHP抓取并回显多个SQL行

时间:2016-03-25 00:11:55

标签: php mysql sql-server

我想用PostID,PostTitle,PostDescription,PostContent等新闻文章信息填充数据库 - 我尝试编写一些代码来不断回显SQL查询中的数据但它只适用于第一个查询选中的行

$SQL = "SELECT * FROM posts"; // get all info from posts
$result = mysql_query($SQL);        
$row = mysql_fetch_array($result);

if (mysql_numrows($result) > 0) {
    $row = mysql_fetch_array($result);
    $Title = $row["PostTitle"];
    $Description = $row["PostDescription"];
    $Date = $row["PostDate"];
    $AuthorID = $row["AuthorID"];

    echo "<div id='preview'>";
        echo "<div class='group selection'>";
            echo "<div class='col span_1_of_3'>"; 
                echo "<div id='previewmedia'>";
                echo "</div>";                        
            echo "</div>";
            echo "<div class='col span_2_of_3'>";
                echo "<h1>".$Title."</h1>";
                echo "<p class='preview'>".$Description."</p>";

                echo "<a href='bloglayout.php' class='orange readmore'>Read More...</a>";
            echo "</div>";
        echo "</div>";
    echo "</div>";                       
}

然后我考虑做一个SELECT查询,然后计算表中ID的数量,然后将其设置为$ ID,然后给每个变量一个数字,然后在每个循环后+1,但意识到这不会有效我有点不知道如何从我的数据库中自动循环出几行。

另外,我知道我不应该在PHP中使用mysql_numrows和whatnot,我应该转移到mysqli或PDO,但这是我被要求专门使用mysql的东西。

1 个答案:

答案 0 :(得分:2)

您只获取一行。尝试循环搜索结果。

$SQL = "SELECT * FROM posts"; // get all info from posts
$result = mysql_query($SQL);        

while( $row = mysql_fetch_array($result);)
{
    $Title = $row["PostTitle"];
    $Description = $row["PostDescription"];
    $Date = $row["PostDate"];
    $AuthorID = $row["AuthorID"];

    echo "<div id='preview'>";
        echo "<div class='group selection'>";
            echo "<div class='col span_1_of_3'>"; 
                echo "<div id='previewmedia'>";
                echo "</div>";                        
            echo "</div>";
            echo "<div class='col span_2_of_3'>";
                echo "<h1>".$Title."</h1>";
                echo "<p class='preview'>".$Description."</p>";

                echo "<a href='bloglayout.php' class='orange readmore'>Read More...</a>";
            echo "</div>";
        echo "</div>";
    echo "</div>";                       
}