Here the while loop will return one row of data as array in each loop execution by using fetch_array() as condition. The record pointer will move to next record after returning present row or record. After returning last record fetch_array() will return NULL which is same as False and while loop will end.
$result is the resultset returned by mysqli_query() or mysqli_store_result() or mysqli_use_result()
$result_type A constant tells which type of row data should be returend. There are three types , MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.
MYSQLI_ASSOC : We get one associative array where we access data by usign field name. Example $row['name']
MYSQLI_NUM : We get one numeric array where we access data by using field index numbers . Example $row[2]
MYSQLI_BOTH : We get both in the array so field names and index number can be used. Example $row['class'], $row[1]
Adding elements to multidimensional array.
We will create amultidimensional array by taking records from a database table. Here we are looping through all the records to display records and at the same time adding the record to array.
Note that each student record is an array and it is added to our main array my_array. While adding to an array we can add one more element ( as percentage here ) for each record.
Here is the full code
<?Php
require "config.php";// Database connection file.
$result_set = $connection->query("SELECT * FROM student ");// Generate resultset
$my_array=array();
while($row = $result_set->fetch_array(MYSQLI_ASSOC)){
$percentage=($row['mark']/200)*100; // new element to be stored in our array
$my_array[]=array("id"=>$row['id'],"name"=>$row['name'],"class"=>$row['class'],"mark"=>$row['mark'],"percentage"=>$percentage);
}
$max=sizeof($my_array);
for($i=0; $i<$max; $i++) {
// displaying all the elements
while (list ($key, $val) = each ($my_array[$i])) {
echo "$key -> $val <br>";
} // inner array while loop
} // outer array for loop
?>
Displaying single element ( record )
echo $my_array[5]['name']; // displaying single record