简体   繁体   中英

How to display results from a MySQL query in a HTML table

I am trying to display the records that are returned from a query in a html table. So when the query is processed the 1st record in the mysql database table (containing the image and the song title) will be displayed in the first block in the html table (Row 1, Column1) below and the 2nd record will be displayed in the second block of the table (Row 1, Column2) and so on, but after three records have been displayed. I would want a new row in the table to be generated

HTML table output should look like this below:

           column 1     column 2     column 3
         -----------------------------------------
         | Image1      | Image2      | Image3      |
row 1 -> | song title1 | song title2 | song title3 |      
         ------------------------------------------
         | Image 4     | Image 5     | Image6      |
row 2 -> | Song title4 | song title5 | song title6 |
         ------------------------------------------

And here is the structure of the table in my mysql database:

search
         ------------------------------
        |  Id   |  image |    song     |
         ------------------------------
row 1-> |   1   | image1 | song title1 |
         ------------------------------
row 2-> |   2   | image2 | song title2 | 
         ------------------------------
row 3-> |   3   | image3 | song title3 |
         ------------------------------


row 4...

So far I can only display the results in a table but I don't know how to structure the table in the format of the html table example I gave above Here is the code I have so far:

while($row = mysql_fetch_assoc($queryset)) {
                        $id = $row['id'];
                        $image = $row['image'];
                        $song = $row['song'];

                        echo '<table style="width:100%">
                                  <tr>

                                    <td>

                                        $image
                                        <br>
                                        $song 

                                    </td>
                                  </tr>
                               </table>';





                    }

I apologies in advance if I have made any mistakes/errors or if I have wasted you time, I'm kind of new to this whole thing.?

What you need is:

  1. to declare a variable counter. Initializes it to be zero at start, and increases it by one when one DB row have been read.

  2. Whenever your counter reaches 2 modulo 3 :

    if($counter % 3 == 2)

then it means you need to add a new line in your html table.

  1. Do not create a table for each element. You need to add

    <td> $image<br /></td>

inconditionnaly. But opening a new line (with tr) depends on 2.

I would suggest, using a modulo operator % to detect each 3rd entry.

Eg (not tested, but should do the trick):

$entryCounter = 0;
$numberOfEntries = mysql_num_rows($queryset);

echo '<table style="width:100%"><tr>';

while($row = mysql_fetch_assoc($queryset)) {
    $id = $row['id'];
    $image = $row['image'];
    $song = $row['song'];

    echo "<td>$image<br />$song</td>";

    if (($entryCounter % 3) == 2 && $entryCounter != $numberOfEntries) 
    {
        echo '</tr><tr>';
    }

    $entryCounter++;

}

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

Please try the below code. Please try use mysqli, I have used that here mysqli_fetch_assoc($queryset). For testing you may change it to mysql_fetch_assoc($queryset).

<table style="width:100%">
<?php $count = 0; /* Since you want 3 rows fetched from database in 3 columns of a row, If am using a count variable to print the column in table.*/
      while($row = mysqli_fetch_assoc($queryset)) { ?>
<?php if($count == 0){ /* will start a new row. */ ?> 
    <tr>
<?php } ?>

<?php if($count < 3){  /* will add columns in row. */ ?> 
    <td>
        <?php $row['image']; ?>
    </br>
        <?php $row['song'];  ?> 
    </td>
<?php } ?>


<?php if($count == 2){ /* will end row when 3 columns are added. */ ?> 
    </tr>
<?php } ?>

<?php $count = ($count++) % 3;  /* will reset the count for new row to start. */ ?> 

<?php } ?>
</table>

I like to use functions (and methods and classes) to organize and split up tasks. This makes things neater, more maintainable and extensible, and supports possible re-use later on.

Also remember to use mysqli or PDO instead of the mysql extension, which is deprecated :

// $where and $order_by correspond to the sql WHERE and ORDER BY clauses
function getSongs($where = null, $order_by = null) {
    $tbl_songs = array();
    /* Put your specific mysqli or PDO code here, which should return a table (array of arrays) using $where: 
    Ex: $tbl_songs[0] = array("id" => 1, "image" => "image1", "song" => "title1");
        $tbl_songs[1] = array("id" => 2, "image" => "image2", "song" => "title2")
    */  
    return $tbl_songs;
}

function viewSong($id, $src, $title) {
    $html = "<img id='$id' src='$src' alt='$title'>\n";
    $html .= "<p>$title</p>\n";
    return $html;
}

function viewSongs($columns = 3, $where = null) {
    $html = null;
    $tbl_songs = getSongs($where);
    if ($tbl_songs) {
        $songs = count($tbl_songs);
        $html = "<table>\n<tr>\n";
        foreach ($tbl_songs as $i => $arr_song) {
            $html .= "<td>" . viewSong($arr_song["id"], $arr_song["image"], $arr_song["song"]) . "</td>\n";
            if (!(($i+1) % $columns) && (($i+1) < $songs)) {
                $html .= "</tr>\n<tr>\n";
            }
        }
        $html .= "</tr>\n</table>\n";
    }
    return $html;
}

$columns = 3;
echo viewSongs($columns);
$html=''; 
$htmlRow='';
$i=1;
while($row = mysql_fetch_assoc($result)) {
  $htmlRow.="<td>".$row[image]."<br>".$row[ song]." </td>"; 
  if($i==3){
    $html.="<tr>$htmlRow</tr>";
    $htmlRow='';
    $i=0;
  }
  $i++;
}

echo $html;
<table>

<?php 
while($row = mysql_fetch_assoc($queryset)) {
?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["image"]; ?></td>
<td><?php echo $row["song"]; ?></td>
</tr>
<?php
}
?>
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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