Pages

Basic PHP Crash Course (part 7)

Saturday, May 12, 2012
In this post, we discuss how to retrieve or select the data from MySQL database to view our pizza order.
To do so we should create admin folder. So that we can prevent the customer from viewing our admin data.

Create a folder named admin in our pizza_shop folder.

Open the new document in your favourite editor or Notepad and type below code.


<html>
<head>
 <title>Amin Pannel</title>
</head>
<body>
<?php
 $con = mysqli_connect('localhost','root','','pizza') or die(mysqli_error());
 $sql="SELECT * FROM `order`";
 $result = mysqli_query($con,$sql) or die(mysqli_error());
 echo "<table width='100%'>";
  echo "<tr bgcolor='#FC0'>".
    "<td width='40%'>Customer Name</td>".
    "<td width='40%'>Address</td>".
    "<td width='20%' align='right'>Quantity</td>".
    "</tr>";
 while($row=mysqli_fetch_array($result)){
  echo "<tr valign='top'>".
    "<td width='40%'>".$row['name']."</td>".
    "<td width='40%'>".$row['address']."</td>".
    "<td width='20%' align='right'>".$row['quantity']."</td>".
    "</tr>";
 }#end of while loop
 echo "</table>";
?>
</body>
</html>

Save above file as index.php in our admin folder. Now if run this address http://localhost/pizza_shop/admin/ from your browser you will see like below.

Explanation

Our sql query is
"SELECT * FROM `order`"
* means all. This query will retrieve all data from our order table of pizza database.


If you familiar with programming, you can follow the code showed above picture. In this code I use while loop to show the order data.

Looping

In every programming, looping is an essential thing. In PHP, there are four kinds of looping. They are while, dowhile, for and foreach. You can use for loop if you know the looping time exactly. You can use dowhile if you want to execute at least once. If you don't know the looping time exactly, you can use while loop. The foreach loop is specially designed for use with arrays.

While Loop

This loop is simplest loop in PHP. It look like if statement. As long as the condition is true, it will execute the block repeatedly.

For our code as long as our order rows exist in our order table of the pizza database, the while loop will show the order rows.
mysqli_fetch_array($result) function will fetch the order table row one by one as an array. If there is no more rows, it will return NULL. When NULL return, while loop will stop.

5 comments: