在 PHP 中使用 MySQL 时,可能需要同时执行多个查询。这对于在单个事务中创建视图、临时表和操作数据非常有用。
考虑以下代码片段:
$query1 = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X"; $query2 = "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)"; $query3 = "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)"; $query4 = "SELECT *, @rank_change = prev_rank - current_rank AS rank_change FROM final_output";
我们的目标是在单个 PHP 脚本中执行所有四个查询,然后使用 mysql_fetch_array 检索第四个查询的结果。但是,当尝试这样做时,我们遇到错误或收到空的获取数组。
要在单个 PHP 脚本中执行多个查询,我们可以使用 mysqli_multi_query。这是更新后的代码:
$link = mysqli_connect("server", "user", "password", "database"); $query = " CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X; CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH); 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); 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']; } mysqli_free_result($result); } } while (mysqli_next_result($link)); }
使用 mysqli_multi_query,我们将所有四个查询连接到一个字符串中并执行它们。然后,每个结果集都存储在 $result 中,并且可以使用 mysqli_fetch_array 进行检索。
也可以单独执行查询并将结果存储在临时表中。例如:
$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']; }
在此方法中,第一个查询创建一个名为 A 的临时表。然后我们在第二个查询中从 A 中选择数据并检索结果。
两种方法都可以根据具体要求和数据库结构来使用。
以上是如何在单个 PHP 脚本中执行多个 MySQL 查询?的详细内容。更多信息请关注PHP中文网其他相关文章!