PHP 中的 MySQL 多个查询
处理复杂的数据库操作时,可能需要在单个 PHP 脚本中执行多个查询。以下是如何使用 PHP 和 MySQL 实现此目的:
在您的情况下,您在尝试将多个查询合并为单个结果时遇到错误。要解决这个问题,关键的解决方案是利用 mysqli_multi_query() 函数。通过连接查询并将它们传递给此函数,您可以按顺序执行它们。
这是使用 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)); }
记住替换“X”在具有适当日期参数的查询中。
替代方法
如果顺序执行查询就足够了,您可以使用多个 mysqli_query() 调用来单独执行每个查询。例如:
$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']; }
以上是如何在 PHP 中高效执行多个 MySQL 查询?的详细内容。更多信息请关注PHP中文网其他相关文章!