Display MySQL database records on a webpage
Here’s a simple example of how to interact with a MySQL database using PHP to display records on a webpage:
PHP
<?php
// Create connection:
$conn = new mysqli ("server", "user", "password", "database");
mysqli_set_charset ($conn, "utf8");
// Check connection:
if ($conn -> connect_error) {
die ("Connection failed: " . $conn->connect_error);
}
// SQL query:
$sql = "SELECT * FROM top_5000_songs LIMIT 0, 10";
$result = $conn -> query($sql);
if ($result -> num_rows > 0) {
// Output each row
while ($row = $result -> fetch_assoc()) {
echo "<div>" . $row["song_title"] . " - " . $row["artist"] . "</div>";
}
}
else {
echo "No records found";
}
$conn -> close();
?>
Explanation:
SELECT
: The keyword used to query data.*
: Represents all columns in the table (you can specify specific columns instead, such ascolumn_01
,column_02
).FROM top_5000_songs
: The table name from which to retrieve the records.
Comma after each value, except the last one
Display records
Display records in a Bootstrap Table
Display records in columns
Display records with Bootstrap pagination
Display records with CSS styles
Escape special characters in a string
Highlight the search term in results
Replace unicode characters by utf-8
Search autocomplete with Typeahead
Search records by an option
Select rows for the current day and month
Short commands