PHP functions for MySql : mysqli_fetch_all()

The mysqli_fetch_all() function fetch all rows and returns the result set as an associative array, a numeric array or both. The syntax is :
mysqli_fetch_all(result, resulttype);
Where :
  • result specifies a result set identifier returned by mysqli_query().
  • resulttype is optional, it specifies what type of array that should be produced. The possble values of resulttype are :  MYSQLI_ASSOCMYSQLI_NUM, MYSQLI_BOTH. The MYSQLI_ASSOC is default one.
Example :
<?php

  $server = "localhost";
  $username = "root";
  $password = "";
  $dbName = "mydb";

  $connection = mysqli_connect($server, $username, $password, $dbName);

  $sql = "SELECT * from employee";
  $result = mysqli_query($connection, $sql);

  $data = mysqli_fetch_all($result, MYSQLI_ASSOC);

  mysqli_close($connection);

?>
To print all the data returned by the database, we have to loop through all rows.

Example :
<?php

  $server = "localhost";
  $username = "root";
  $password = "";
  $dbName = "mydb";

  $connection = mysqli_connect($server, $username, $password, $dbName);

  $sql = "SELECT * from employee";
  $result = mysqli_query($connection, $sql);

  $row = mysqli_fetch_all($result, MYSQLI_ASSOC);
  $rowcount = mysqli_num_rows($result);

  // iterate through each row
  for($i = 0; $i < $rowcount; $i++) {
    echo $row[$i]["EmpId"] . " : " . $row[$i]["EmpName"] . "<br/>";
  }

  mysqli_close($connection);

?>
Output :

101 : John
102 : Marry
103 : Sam
104 : Bruce
105 : Clark Kent
106 : Jack


Next Topic :