May 11, 2021 PHP
Select statements are used to read data from a data table:
SELECT column_name(s) FROM table_name
We can read the fields in all data tables using the number:
SELECT * FROM table_name
To learn more about SQL, visit our SQL tutorial.
In the following example we read the data for the id, firstname, and lastname columns from the table MyGuests and display it on the page:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
Detect the connection
if ($conn->connect_error) {
die("Connection failed: " .
$conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
Output each row of data
while($row = $result->fetch_assoc()) {
echo "id: ". $
row["id"]. "
- Name: ". $
row["firstname"]. "
" . $
row["lastname"].
"<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
The following instance reads all the records of the MyGuests table and displays them in the HTML table: