PHP Select Data From MySQL

So far you have learnt how to create database and table as well as inserting data. Now it's time to retrieve data what have inserted in the preceding tutorial. The SQL SELECT statement is used to select the records from database tables

First, we set up an SQL query that selects the id, firstname and lastname columns from the MyGuests table. The next line of code runs the query and puts the resulting data into a variable called $result. Then, the function num_rows() checks if there are more than zero rows returned.

Example -

Explanation of Code (Procedural style)

In the example above, the data returned by the mysqli_query() function is stored in the $result variable. Each time mysqli_fetch_array() is invoked, it returns the next row from the result set as an array. The while loop is used to loops through all the rows in the result set. Finally the value of individual field can be accessed from the row either by passing the field index or field name to the $row variable like $row['id'] or $row[0], $row['first_name'] or $row[1], $row['last_name'] or $row[2], and $row['email'] or $row[3].

If you want to use the for loop you can obtain the loop counter value or the number of rows returned by the query by passing the $result variable to the mysqli_num_rows() function. This loop counter value determines how many times the loop should run.

Example -