PHP MySQL: Display records using fetch_array

We have looked at retrieving records using associative array and numeric array.

  • fetch_assoc()
  • fetch_row()

There is a third type fetch_array provided by PHP where you can use both types of array.

Syntax:  mixed mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] )

We take a brief look at this type of method.

$mysqli = new mysqli("localhost", "root", "", "allartist");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());

$query = "select * from artist";
$result = $mysqli->query($query);

/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s %s", $row[0], $row[1]);
echo "<br>";

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s %s", $row["id"], $row["artiste"]);
echo "<br>";

/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf ("%s %s", $row[0], $row["artiste"]);

/* free result set */

/* close connection */

The output from running the above script is as below:



This optional parameter is a constant indicating what type of array should be produced from the current row data.

The possible values for this parameter are the constants:

  • MYSQLI_NUM, or

By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function.

The final option MYSQLI_BOTH will create a single array with the attributes of both.

Series Navigation<< PHP MySQL: Display records using fetch_row()
PHP MySQL: Select a single record using fetch_assoc >>