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':
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':
<?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>"; ?>
<?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 "◉ " . $row["song"] . ""; // last row: no comma, no space after
} else {
echo "◉ " . $row["song"] . ", ";
}
}
}
else {
echo "No records found";
}
$conn -> close();
?>