home

Php Select From Db Tutorial


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.

<?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 

<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>

 


Content on this page requires a newer version of Adobe Flash Player.

Get Adobe Flash player

Copyright © 2014 by Cramerz.com.