在MySQL中从数据库中获取每个记录数后显示一个新的div

时间:2017-04-17 22:18:24

标签: php mysql

我想在我正在处理的项目上为广告创建一个div。我希望在从数据库中获取8条记录后显示div。

我的选择陈述:

$query = mysql_query("SELECT * FROM  posts WHERE `username` = '$followe' OR `user_id` = ' $get_id' ORDER BY date_added DESC LIMIT 15 ");
$newsCount = mysql_num_rows($query); // Count the output amount

if ($newsCount > 0) {
    while($row = mysql_fetch_assoc($query)){
        $id = $row["id"];
        $user_post_id = $row["user_id"];
        $username = $row["username"];
        $text =     $row["texts"];
        $profile_pix = $row["profile_pix"];
    }
}

2 个答案:

答案 0 :(得分:1)

您需要为while循环添加一个计数器,并在计数器可被8整除时回显HTML字符串:

<?php
    $query = mysql_query("SELECT * FROM  posts WHERE `username` = '$followe' OR `user_id` = ' $get_id' ORDER BY date_added DESC LIMIT 15 ");
    $newsCount = mysql_num_rows($query); // Count the output amount

    if ($newsCount > 0) {
        $rowcount=1;
        $divhtml = "<div></div>";
        while ($row = mysql_fetch_assoc($query)){
             if ($rowcount % 8 == 0) {
                 echo $divhtml;
             }
             $rowcount++;

             $id = $row["id"];
             $user_post_id = $row["user_id"];
             $username = $row["username"];
             $text =     $row["texts"];
             $profile_pix = $row["profile_pix"];
        }
    }
?>

您应该使用自己的广告HTML更改变量$ divhtml的内容。

答案 1 :(得分:0)

使用这样的累加器模式。

          $i = 0
          while($row = mysql_fetch_assoc($query)){
              $i++;
              if(i == 8) {
                  // DO WHATEVER 
              }
              $id = $row["id"];
              $user_post_id = $row["user_id"];
              $username = $row["username"];
              $text =     $row["texts"];
              $profile_pix = $row["profile_pix"];
          }