显示字母子标题中表格的数据

时间:2014-02-09 14:01:50

标签: php mysqli

我试图从表格中显示我的数据索引,并决定我想要小标题,例如

A
apple
ant
ape

...

Z
zoo
zebra

有没有可以做到这一点的功能?

这是我的代码,我没有尝试任何东西,因为不确定我正在寻找的功能

<?php
//include database connection
include 'inc/dbcon.php';

//query all records from the database
$query = "select *
                        from db ORDER BY item ASC";

//execute the query
$result = $mysqli->query( $query );

//get number of rows returned
$num_results = $result->num_rows;

//this will link us to our add.php to create new record
if( $num_results > 0){ //it means there's already a database record

    //start table
    //creating our table heading


    //loop to show each records
    while( $row = $result->fetch_assoc() ){
            //extract row
            //this will make $row['firstname'] to
            //just $firstname only
            extract($row);

            //creating new table row per record
            echo "<h2>{$item}</h2><br>";
echo "";

    }

    echo "";

}else{
    //if database table is empty
    echo "Shit out of luck there is No records found.";
}

//disconnect from database
$result->free();
$mysqli->close();

?>

此刻正在给我一个清单

1 个答案:

答案 0 :(得分:1)

您可以为while循环执行此操作:

    $letter = "";
while( $row = $result->fetch_assoc() )
{
    //extract row
    //this will make $row['firstname'] to
    //just $firstname only
    extract($row);

    //creating new table row per record
    if(substr(strtoupper($item),0,1) != $letter)
    {
        $letter = substr(strtoupper($item),0,1);
        echo("<h2>$letter</h2><br>");
    }
    echo "<h2>{$item}</h2><br>";
}