In previous tutorials we have to learned create database,create table,insert data in table.
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.
Its basic syntax is as follows:
SELECT column1_name, column2_name, columnN_name FROM table_name;
or
SELECT * FROM table_name
The PHP code in the following example selects all the data stored in the persons table (using the asterisk character (*) in place of column name selects all the data in the table.
In these example we can selects id,firstname and lastname from the tables
After that we will execute this SQL query through passing it to the PHP mysqli_query()
function to retrieve the table data.
output : Below picture showing Selected columns (id,firstname,lastname )data retreive in database table name "Employee" , as we can see :
function num_rows()
checks if there are more than zero rows returned., it returns the next row from the result set as an array. If there are more than zero rows returned, the function fetch_assoc()
puts all the results into an associative array that we can loop through. 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]
.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 num_rows()
function. This loop counter value determines how many times the loop should run.Output :
We can also put the result in an HTML table:
Html table (Mysqli object oriented example ) :
Output :