PHP Tutorial - PHP mysqli_multi_query() Function






Definition

The mysqli_multi_query() function performs one or more queries separated with a semicolon against the database.

Syntax

Object oriented style

bool mysqli::multi_query ( string $query )

Procedural style

bool mysqli_multi_query ( mysqli $link , string $query )

Parameter

ParameterIs RequiredDescription
connectionRequired.MySQL connection
queryRequired.One or more queries seperated with semicolon

Return

It returns FALSE if the query fails.

Example

The following code performs multiple queries against the database.


<?php//from w  w w.  j  a va 2  s.co m
$con=mysqli_connect("localhost","my_user","my_password","my_db");

if (mysqli_connect_errno($con)){
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "SELECT Lastname FROM Persons;SELECT Country FROM Customers";

// Execute multi query
if (mysqli_multi_query($con,$sql)){
  do{
    // Store first result set
    if ($result=mysqli_store_result($con)){
      while ($row=mysqli_fetch_row($result)){
        printf("%s\n",$row[0]);
      }
      mysqli_free_result($con);
    }
  }while (mysqli_next_result($con));
}

mysqli_close($con);
?>




Example 2


<?php// w w  w .  j a va2 s . c  om
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();SELECT Name FROM City";

if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

$mysqli->close();
?>