选择特定的MYSQL行

亚历克斯

我有一个页面,假设该页面为数据库中的每9个条目创建一个Div。每个Div将包含3个UL,每个UL将包含3个LI。像这样的东西:

演示版

因此,每个LI都是显示每个条目的位置,每个Div本质上都是一个唯一的页面。

到目前为止,这是我的代码:

    $sql = mysql_query("SELECT * FROM `reviews`") or die(mysql_error());
    $e_count = mysql_num_rows($sql);
    $r_pages = ceil($e_count / 9);
    $x = 1;
    $y = 1;
    if($e_count > 9){ // if there are more than 9 entries in the database           
        for($x=1;$x<=$r_pages;$x++){ // creates a div for every 9 items in the database 
            echo '<div class="rp_pages" id="rp_page_'.$x.'">';
                for($y=1;$y<=3;$y++){ // creates 3 ULS in each "page" 
                    echo '<ul>';
                       // 3 lis should appear here      
                    echo '</ul>';                       
                }
            echo '</div>';
        }                           
    }

问题是,我不想使用多个带有LIMIT的查询来选择相应的条目。只需一个查询就能完成吗?

豪尔赫·富恩特斯·冈萨雷斯

我只看到一个查询(第一个选择)。之后,不要用它来计算行数,而是解析每行并提取审阅文本,方法是:

假设该reviews表有一个text列,用于保存审阅文本。拥有您的代码:

$sql = mysql_query("SELECT * FROM `reviews`") or die(mysql_error());
$e_count = mysql_num_rows($sql);
$r_pages = ceil($e_count / 9);
$x = 1;
$y = 1;
if($e_count > 9){ // if there are more than 9 entries in the database           
    for($x=1;$x<=$r_pages;$x++){ // creates a div for every 9 items in the database 
        echo '<div class="rp_pages" id="rp_page_'.$x.'">';
            for($y=1;$y<=3;$y++){ // creates 3 ULS in each "page" 
                echo '<ul>';

                // Here the code that extract the rows from the query.
                for($z=1;$z<=3;$z++){
                    echo '<li>';
                    if($data = mysql_fetch_array($sql, MYSQL_ASSOC)) {
                        echo $data['text']; // Use some type of parser to show special characters like < or > as text, so you are safe from code injection.
                    }
                    echo '</li>';
                }


                echo '</ul>';                       
            }
        echo '</div>';
    }                           
}

如您所见,它创建了一个新的循环来创建3 lis,并在每个循环li提取text查询中所选的内容,然后使用echo它。

正如http://php.net/manual/en/function.mysql-fetch-array.php所说:

返回与获取的行相对应的数组,并将内部数据指针向前移动。

因此,下一次您获取一行时,它将是下一个。

PD:mysql不推荐使用PHP 使用mysqli代替。是一样的,但是与另一个正在开发中的库(不是一样)mysql

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章