Logo Luan Morina
Count Rows Demo
Abba has 20 songs in the top 5000 list

The COUNT() function returns the number of rows in a table. Here is an example with records from a table named top_5000_songs (song, artist, year) WHERE `artist` = 'abba':

Count Rows

<?php
$conn = new mysqli ("server", "user", "password", "database");
mysqli_set_charset ($conn, "utf8");
if ($conn -> connect_error) {die ("Database Connection Error!");}

$sql = "SELECT * FROM top_5000_songs WHERE `artist` = 'abba' ORDER BY year ASC";
$result = $conn -> query($sql);
$row_count = $result->num_rows;

while ($row = $result -> fetch_assoc()) {
echo "<div>" . $row["song"] . "  (" . $row["artist"] . ", " . $row["year"] . ")</div>";

}
$conn -> close();
?>

<?php echo "<p>" . $row_count . " rows </div>"; ?>

Count Rows Demo

<?php
$conn = new mysqli ("server", "user", "password", "database");
mysqli_set_charset ($conn, "utf8");
if ($conn -> connect_error) {die ("Database Connection Error!");}

$sql = "SELECT * FROM top_5000_songs WHERE `artist` = 'abba' ORDER BY year ASC";
$result = $conn -> query($sql);

if ($result -> num_rows > 0) {
$count_results = mysqli_num_rows($result); 
$count_results_before_last_row = mysqli_num_rows($result)-1;
$count_titles = 0; 

while ($row = $result -> fetch_assoc()) {

if (++$count_titles == $count_results) {
echo "◉&nbsp;" . $row["song"] . "";  // last row: no comma, no space after
} else {
echo "◉&nbsp;" . $row["song"] . ", &nbsp;&nbsp;";
} 

}
} 
else {
echo "No records found";
}
$conn -> close();
?>
   Count the total number of rows in a table