简体   繁体   English

我使用mysqli_fetch_assoc()以递减的顺序获取数组,并以不同的方式获取。我如何纠正它?

[英]I used mysqli_fetch_assoc() to fetch the array in decreasing order and it fetches in a different manner.How can I correct it?

I used mysqli_fetch_assoc function to fetch the rows in a decreasing order but when I echo the associative array of table "posts"(there are only three rows in the posts table- post 1,post 2 , post 3) 我使用mysqli_fetch_assoc函数以递减的顺序获取行,但是当我回显表“posts”的关联数组时(posts表中只有三行 - post 1,post 2,post 3)

it prints in this manner:( I have added a screenshot of this output ) 它以这种方式打印:( 我已添加此输出的屏幕截图

post 3 (edit/delete) 帖子3(编辑/删除)

post 3 (edit/delete) 帖子3(编辑/删除)
post 2 (edit/delete) 帖子2(编辑/删除)

post 3 (edit/delete) 帖子3(编辑/删除)
post 2 (edit/delete) 帖子2(编辑/删除)
post 1 (edit/delete) 帖子1(编辑/删除)

I wanted it to print in this manner: 我希望它以这种方式打印:

post 3 (edit/delete) 帖子3(编辑/删除)
post 2 (edit/delete) 帖子2(编辑/删除)
post 1 (edit/delete) 帖子1(编辑/删除)

Here is my code: 这是我的代码:

    <?php
    $db = mysqli_connect("localhost", "root", "", "myblog");
    $sql = "SELECT * FROM posts ORDER BY id DESC";
    $res = mysqli_query($db, $sql) or die(mysqli_error($db));
    $count = mysqli_num_rows($res);
    $posts = "";

    if ($count > 0) {
      while ($row = mysqli_fetch_assoc($res)) {
        $id = $row['id'];
        $title = $row['title'];
        $content = $row['content'];
        $date = $row['date'];


        $admin = "
               <div>
               <a href='del_post.php?pid=$id'>DELETE </a>
               <a href='edit_post.php?pid=$id'>EDIT</a>
               </div>
               ";
        $posts .= "<div><h4>$title</h4><h3>$date</h3><p>$content</p>$admin</div>";

        echo $posts;
      }
    } else {
      echo "there is nothing to show";
    }

    ?>

Thanks. 谢谢。

I think the the problem is in this line, 我认为问题出在这一行,

while ($row = mysqli_fetch_assoc($res)

need to change $res for $count instead. 需要更改$ res而不是$ count。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM