MySQL Select Data

PHP MySQL Select Data

Now that we have inserted data into our database, we need to know how to read it back out!

To retrieve data from a database table, we use the SELECT statement.


The SELECT Statement

You can select specific columns: SELECT firstname, lastname FROM MyGuests

Or you can select all columns using the asterisk (*) character: SELECT * FROM MyGuests

Select Data Example

<?php
$servername = "localhost";
$username = "root";
$password = "your_password";
$dbname = "myDB";

$conn = mysqli_connect($servername, $username, $password, $dbname);

$sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql);

// mysqli_num_rows() checks if there are more than zero rows returned if (mysqli_num_rows($result) > 0) {

// Fetch associative array row by row using a while loop while($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . "<br>"; }

} else { echo "0 results found."; }

mysqli_close($conn); ?>

Understanding mysqli_fetch_assoc()

The mysqli_fetch_assoc() function fetches the next row of the result set as an associative array. The loop continues until there are no more rows left, making it incredibly easy to format your database outputs into HTML lists or tables!


Exercise

?

Which character is used in a SELECT statement to retrieve ALL columns from a table?