MySQL Multi Query 存储结果第二次查询

MySQL Multi Query store result second query

我在这里从数据库中的两个不同表进行查询,我可以存储第一个查询的值,但是如何存储第二个查询的信息?

$query  = "SELECT * ";
$query .= "FROM user_account ";
$query .= "WHERE user_id = $user_id ";
$query .= "SELECT * ";
$query .= "FROM user_profile ";
$query .= "WHERE user_id = $user_id ";


if (mysqli_multi_query($mysqli, $query)) {
    do {
        if ($result = mysqli_store_result($mysqli)) {
            while ($row = mysqli_fetch_row($result)) {
                $Firstname = $row['Firstname'];
                $Lastname = $row['Lastname'];
                $Email = $row['Email'];
                $Birthday = $row['Birthday'];
                $Address = $row['Address'];
                $Zip = $row['Zip'];
                $City = $row['City'];
                $State = $row['State'];
                $Country = $row['Country'];
                $Avatar = $row['Avatar']; Will be added later
                $Phone = $row['Phone'];
                $Website = $row['Website'];
                $Member_level = $row['Member_level'];
            }
            mysqli_free_result($result);
        }
        if (mysqli_more_results($mysqli)) {
        }
        while (mysqli_next_result($mysqli)) ;
    }
}

在您的代码中,为什么要使用 mysqli_free_result 函数,因为它会释放与结果对象关联的内存,因此当 while 循环时 运行 它不会显示任何结果。

$query  = "SELECT * FROM user_account WHERE user_id = $user_id ";
$query .= "SELECT * FROM user_profile WHERE user_id = $user_id ";

if (mysqli_multi_query($mysqli, $query)) {
     do {
      if ($result = mysqli_store_result($mysqli)) {
           while ($row = mysqli_fetch_assoc($result)) {
               var_dump($row); //for checking result 
              // Now use array to show your result
          }

     } }while (mysqli_next_result($mysqli)) ;

You should always free your result with mysqli_free_result(), when your result object is not needed anymore.

按照常规方式

$query = "SELECT * FROM user_account WHERE user_id = $user_id ";
$account = $mysqli->query($query)->fetch_assoc();

$query = "SELECT * FROM user_profile WHERE user_id = $user_id ";
$profile = $mysqli->query($query)->fetch_assoc();

就这么简单。

我真的很想知道为什么 PHP 用户倾向于编写如此多的代码并为最琐碎的操作使用如此复杂的方法

附带说明一下,在您的特定情况下,您可以编写单个 JOIN 查询。