Melaksanakan Berbilang Pertanyaan dalam PHP/MySQL
Masalah:
Melaksanakan berbilang pertanyaan bebas dan menggabungkan keputusan menjadi satu hasil yang padu menggunakan PHP dan MySQL boleh menimbulkan a cabaran.
Penyelesaian:
1. mysqli_multi_query()
Contoh:
// 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. Asingkan Pertanyaan
Contoh:
// 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... }
Atas ialah kandungan terperinci Bagaimanakah Saya Boleh Melaksanakan dan Menggabungkan Berbilang Pertanyaan MySQL dengan Cekap dalam PHP?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!