Home >Database >Mysql Tutorial >How to Execute Multiple MySQL Queries Efficiently in PHP?

How to Execute Multiple MySQL Queries Efficiently in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 07:13:11605browse

How to Execute Multiple MySQL Queries Efficiently in PHP?

MySQL Multiple Queries in PHP

When dealing with complex database operations, executing multiple queries in a single PHP script can be necessary. Here's how to achieve it using PHP and MySQL:

In your case, you were encountering errors while attempting to merge multiple queries into a single result. To resolve this, the key solution is to utilize mysqli_multi_query() function. By concatenating your queries and passing them to this function, you can execute them sequentially.

Here's a revised version of your code using mysqli_multi_query():

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

$query = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X;";
$query .= "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH);";
$query .= "CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank AS current_rank, previous_rankings.rank AS prev_rank FROM current_rankings LEFT JOIN previous_rankings ON (current_rankings.player = previous_rankings.player);";
$query .= "SELECT *, @rank_change = prev_rank - current_rank AS rank_change FROM final_output;";

if (mysqli_multi_query($link, $query)) {
    do {
        if ($result = mysqli_store_result($link)) {
            while ($row = mysqli_fetch_array($result)) {
                echo $row['player'] . ' ' . $row['current_rank'] . ' ' . $row['prev_rank'] . ' ' . $row['rank_change'] . '<br>';
            }
            mysqli_free_result($result);
        }
    } while (mysqli_next_result($link));
}

Remember to replace "X" in the queries with the appropriate date parameter.

Alternative Approach

If executing queries sequentially is sufficient, you can use multiple mysqli_query() calls to execute each query individually. For example:

$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'];
}

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

Statement:
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