如何合并两个不同MySQL主机的查询结果变量
问题分析与解决
你犯的核心错误是:get_result()返回的是mysqli_result对象,不是直接的数组,所以直接用array_merge合并两个对象完全无效,后续的->num_rows调用和数组遍历自然都会出错。
修正步骤
- 将结果对象转为数组:对每个查询结果调用
fetch_all(MYSQLI_ASSOC),把结果集转换成二维关联数组 - 合并数组:用
array_merge合并两个二维数组 - 遍历合并后的数组生成表格
完整修正代码
// 执行第一个查询并转成数组 $stmt_ch = $conn_1->prepare("SELECT ts,number from blocklist where number like ?"); $stmt_ch->bind_param('s', $num_remove); $stmt_ch->execute(); $result_ch = $stmt_ch->get_result(); $rows_ch = $result_ch->fetch_all(MYSQLI_ASSOC); // 转为二维数组 // 执行第二个查询并转成数组 $stmt_ch2 = $conn_2->prepare("SELECT ts,number from blocklist where number like ?"); $stmt_ch2->bind_param('s', $num_remove); $stmt_ch2->execute(); $result_ch2 = $stmt_ch2->get_result(); $rows_ch2 = $result_ch2->fetch_all(MYSQLI_ASSOC); // 转为二维数组 // 合并两个数组 $result_ch_com = array_merge($rows_ch, $rows_ch2); // 生成表格 if(count($result_ch_com) > 0){ $output .= ' <table class="table table-bordered"> <tr> <th width="25%" style="text-align:center">Blocked Time</th> <th width="20%" style="text-align:center">Blocked Number</th> </tr> '; foreach($result_ch_com as $row) { $output .= ' <tr> <td style="text-align:center">'.$row['ts'].'</td> <td style="text-align:center">'.$row['number'].'</td> </tr> '; } $output .= '</table>'; echo $output; }
补充说明
如果查询返回的数据量很大,一次性转数组可能占用过多内存,可以改用逐行读取合并的方式:
$result_ch_com = []; // 读取第一个结果集的每一行 while($row = $result_ch->fetch_assoc()){ $result_ch_com[] = $row; } // 读取第二个结果集的每一行 while($row = $result_ch2->fetch_assoc()){ $result_ch_com[] = $row; }
内容的提问来源于stack exchange,提问作者ShEi
相关产品推荐
相关产品推荐

