2

我在以所需格式从 db 检索数据时遇到问题。我用过 PHP MYSQL。我可以使用while($row=mysql_fetch_array($result));等等来检索记录......但不是我想要的格式。

假设,从 db 我得到 10 条记录作为 1 到 10 垂直,但我想要以下格式使用表。

1 2 3 4

5 6 7 8

9 10

注意:没有记录本质上是动态的,我希望每行有 4 列。

请帮帮我。提前致谢。

4

5 回答 5

2

你不能用 MySQL 做到这一点,MySQL 不是用来很好地显示你的数据,它只用于存储和检索你的数据。

您需要的是以下内容,而 $array 可以替换为数据库中的数据:

$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

echo '<table>';
    echo '<tr>';
for ($i = 0; $i < sizeof($array); $i++) {
    if(($i % 4) == 0 && $i != 0) {
        echo '</tr><tr>';
    }
    echo '<td>';
        echo $array[$i];
    echo '</td>';
}
    echo '</tr>';
echo '</table>';
于 2012-12-27T10:24:00.147 回答
1

Having 4 records per row in the database is not changing anything. There's no such a feature in database because it serves no purpose and can be achieved using PHP instead. As stated in the comments databases are not designed for data representation.

You can instead retrieve those data and store them as group of fours later using a simple PHP script:

$i = 0;
$in = 0;
$array = array();
while($row = mysql_fetch_array($result)) {
    if ($i%4) {
        $in++;
    }
    $array[$in][] = $result;
    $i++;
}
于 2012-12-27T10:21:00.783 回答
0

正如juergen d所说 ,SQL 不是为数据表示而设计的。在你的逻辑中处理它

这样你就可以

$array = array(1,2,3,4,5,6,7,8,9,10);
$i=0;

while($i < sizeof($array ) )
{
 if($i%4 ==0 && $i>0) echo "<br>";
  echo $array[$i++] ;
}

注意$array用数据库中的数组替换

于 2012-12-27T10:24:36.790 回答
0
$data = ... your mysqli call that returns the data from mysql
$i = 0;
if ($data) {
    $HTML = '<table><tr>';
    foreach($data as $k => $v) {
         $HTML .= '<td>'.$v.'</td>';
         if ($i == 3) {
             $i = 0;
             $HTML .= '</tr><tr>';
         }
         $i++;
    }
    $HTML .= '</tr></table>';
    echo $HTML;
}
于 2012-12-27T10:24:45.197 回答
0

这是完整的示例 :) .. 您需要在 MYSQL 中使用“Cname”列创建表“Category”

<?php 
    require 'ConnDB.php';
    $sql = "Select * From Category";
    $ResShowCateg = mysqli_query($conn_link, $sql); 

    echo '<table>';
    echo '<tr>';

    for ($i = 0; $i < mysqli_num_rows($ResShowCateg); $i++) {
        $row = mysqli_fetch_assoc($ResShowCateg);
        if(($i % 3) == 0 && $i != 0){
            echo '</tr><tr>';
        }
        echo '<td>';
        echo $row["Cname"];
        echo '</td>';
    }

    echo '</tr>';
    echo '</table>';

    mysqli_close($conn_link);
?>
于 2016-10-13T21:36:18.277 回答