Home > Backend Development > PHP Tutorial > How to Execute Multiple Queries in PHP using MySQL?

How to Execute Multiple Queries in PHP using MySQL?

Mary-Kate Olsen
Release: 2024-11-12 04:48:02
Original
975 people have browsed it

How to Execute Multiple Queries in PHP using MySQL?

Executing Multiple Queries in PHP using MySQL

Scenario:

You have multiple SQL queries that need to be executed together and the results combined. However, you're facing challenges in executing them seamlessly.

Solution 1: Using mysqli_multi_query

To execute multiple queries simultaneously, you can use the mysqli_multi_query() function. Here's how:

$link = mysqli_connect("server", "user", "password", "database");

$query = "QUERY1; QUERY2; QUERY3; QUERY4;";

if (mysqli_multi_query($link, $query)) {
    do {
        if ($result = mysqli_store_result($link)) {
            while ($row = mysqli_fetch_array($result)) {
                // Process results for current query
                echo $row['column1'];
            }
            mysqli_free_result($result);
        }
    } while (mysqli_next_result($link));
}
Copy after login

Solution 2: Separate Query Execution

If you prefer to execute the queries separately, you can do so as follows:

$query1 = "Create temporary table A select c1 from t1";
mysqli_query($link, $query1) or die(mysqli_error());

$query2 = "select c1 from A";
$result2 = mysqli_query($link, $query2) or die(mysqli_error());

while ($row = mysqli_fetch_array($result2)) {
    echo $row['c1'];
}
Copy after login

Remember to replace the server, user, password, and database values with the appropriate details for your database connection.

The above is the detailed content of How to Execute Multiple Queries in PHP using MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template