For the following example, we will assume we have already connected to a database called examples (and we have a $dbc already) and the database contains a table called users with ids, names and surnames.
Scenario. We want to retrieve all the data from users table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?php //CREATING A SELECT QUERY $q = "SELECT * FROM `examples`.`users` ORDER BY `users`.`id` ASC"; //EXECUTING THE QUERY $r = mysqli_query($dbc, $q); //THIS IS AN EMPTY ARRAY TO HOLD THE RESULTS $users = array(); //CHECK IF THE REQUEST RETURNS AT LEAST A ROW //with mysqli_num_rows(mysqli_result) if(mysqli_num_rows($r)>0){ //loop inside results.. //and create an associative array from the result //using mysqli_fetch_assoc(mysqli_result) while($row = mysqli_fetch_assoc($r)){ //inserting results in the users array array_push($users, $row); }//end while loop }//end if numRows //you will have now a multidimensional associative array ($users) //with all the data from users table //displaying $users content echo "<pre>"; print_r($users); echo "</pre>"; /* Array ( [0] => Array ( [id] => 1 [name] => john [surname] => doe ) [1] => Array ( [id] => 2 [name] => james [surname] => bond ) [...] ) */ ?> |
We can now loop through the $users array to display our result in HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<table border="1" cellpadding="10"> <tr> <th>ID</th> <th>NAME</th> <th>SURNAME</th> </tr> <?php foreach($users as $user){ ?> <tr> <td><?php echo $user['id'];?></td> <td><?php echo $user['name'];?></td> <td><?php echo $user['surname'];?></td> </tr> <?php }//end foreach?> </table> |