Maison >base de données >tutoriel mysql >Comment puis-je exécuter et combiner efficacement plusieurs requêtes MySQL en PHP ?
Exécution de plusieurs requêtes en PHP/MySQL
Problème :
Exécution de plusieurs requêtes indépendantes et combiner les résultats en un résultat unique et cohérent en utilisant PHP et MySQL peut poser un problème. défi.
Solutions :
1. mysqli_multi_query()
Exemple :
// establish MySQL connection $link = mysqli_connect("server", "user", "password", "database"); // define multiple queries $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 LEFT JOIN previous_rankings.rank as prev_rank ON (current_rankings.player = previous_rankings.player);"; $query .= "SELECT *, @rank_change = prev_rank - current_rank as rank_change from final_output;"; // execute multiple queries if (mysqli_multi_query($link, $query)) { // loop through each result set do { if ($result = mysqli_store_result($link)) { // fetch data from each result set while ($row = mysqli_fetch_array($result)) { // process the data... } // free result set memory mysqli_free_result($result); } } while (mysqli_next_result($link)); } else { // handle query execution error }
2. Requêtes séparées
Exemple :
// establish MySQL connection $link = mysqli_connect("server", "user", "password", "database"); // execute first query $query1 = "Create temporary table A select c1 from t1"; $result1 = mysqli_query($link, $query1) or die(mysqli_error()); // execute second query $query2 = "select c1 from A"; $result2 = mysqli_query($link, $query2) or die(mysqli_error()); // fetch data from second query while ($row = mysqli_fetch_array($result2)) { // process the data... }
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!