使用 MySQL 在 PHP 中运行多个查询
考虑一个场景,您需要在单个 PHP 脚本中执行多个 SQL 查询。一种常见的方法是使用 mysqli_multi_query() 函数,它允许您将多个查询连接到一个字符串中。
以下是如何实现此目的的示例:
// Create database connection $conn = mysqli_connect('server', 'user', 'password', 'database'); // Construct the multiple queries as a single string $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 the multiple queries if (mysqli_multi_query($conn, $query)) { // Process each result set do { // Check for the first result set if ($result = mysqli_store_result($conn)) { // Fetch and display the results while ($row = mysqli_fetch_array($result)) { echo $row['player'] . ' ' . $row['current_rank'] . ' ' . $row['prev_rank'] . ' ' . $row['rank_change']; } // Free the result set mysqli_free_result($result); } } while (mysqli_next_result($conn)); } else { // Handle any errors echo mysqli_error($conn); }
或者,如果您希望单独执行每个查询,可以使用 mysqli_query() 函数多个times:
// Create temporary table A $query1 = "Create temporary table A select c1 from t1"; mysqli_query($conn, $query1) or die(mysqli_error($conn)); // Select from temporary table A $query2 = "select c1 from A"; $result2 = mysqli_query($conn, $query2) or die(mysqli_error($conn)); // Fetch and display the results while ($row = mysqli_fetch_array($result2)) { echo $row['c1']; }
选择通过 mysqli_multi_query() 将多个查询连接成单个字符串还是通过 mysqli_query() 单独执行它们取决于您的具体要求和性能考虑。
以上是如何在 PHP 中高效运行多个 MySQL 查询?的详细内容。更多信息请关注PHP中文网其他相关文章!