MySQLi Tutorial MySQLi References

mysqli next_result() Method



The mysqli::next_result() / mysqli_next_result() function is used to prepare next result set from a previous call to mysqli_multi_query() which can be retrieved by mysqli_store_result() or mysqli_use_result().

Syntax

//Object-oriented style
public mysqli::next_result()

//Procedural style
mysqli_next_result(mysql)

Parameters

mysql Required. For procedural style only: Specify a mysqli object returned by mysqli_connect() or mysqli_init().

Return Value

Returns true on success or false on failure. Also returns false if the next statement resulted in an error, unlike mysqli_more_results().

Example: Object-oriented style

The example below shows the usage of mysqli::next_result() method.

<?php
//establishing connection to the database
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

//string containing multiple queries
$sql = "SELECT CURRENT_USER();";
$sql .= "SELECT Name FROM Employee";

//executing multiple queries
$mysqli->multi_query($sql);
do {
  //storing the result set in PHP
  if ($result = $mysqli->store_result()) {
    while ($row = $result->fetch_row()) {
      printf("%s\n", $row[0]);
    }
  }

  //if there are more result-sets, printing divider
  if ($mysqli->more_results()) {
    printf("--------------\n");
  }
} while ($mysqli->next_result());

//closing the connection
$mysqli->close();
?>

The output of the above code will be similar to:

user@localhost
--------------
Marry
Kim
John
Adam

Example: Procedural style

The example below shows the usage of mysqli_next_result() function.

<?php
//establishing connection to the database
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

//string containing multiple queries
$sql = "SELECT CURRENT_USER();";
$sql .= "SELECT Name FROM Employee";

//executing multiple queries
mysqli_multi_query($mysqli, $sql);
do {
  //storing the result set in PHP
  if ($result = mysqli_store_result($mysqli)) {
    while ($row = mysqli_fetch_row($result)) {
      printf("%s\n", $row[0]);
    }
  }
  
  //if there are more result-sets, printing divider
  if (mysqli_more_results($mysqli)) {
    printf("--------------\n");
  }
} while (mysqli_next_result($mysqli));

//closing the connection
mysqli_close($mysqli);
?>

The output of the above code will be similar to:

user@localhost
--------------
Marry
Kim
John
Adam

❮ MySQLi Functions Reference