[英]How to add results of multiple queries to an array in PDO?
Below is my code 下面是我的代码
$stmt = $db->prepare("SELECT * FROM inbox ORDER BY `date` DESC ");
$stmt->execute(array());
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$uniques = count(array_unique($row, SORT_REGULAR));
for ($i=0; $i < $uniques; $i++) {
$inbox_id = $row[$i]["inbox_id"];
$stmt = $db->prepare("SELECT * FROM messages WHERE inbox_id=? AND seen=? ORDER BY `date` DESC");
$stmt->execute(array($inbox_id, 0));
$row_msg = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
return $row_msg;
But this is nor returning all data.It is only returning values got from first iteration only. 但这也不是返回所有数据,仅返回第一次迭代得到的值。
您可以使用:
$row_msg[$i] = $stmt->fetchAll(PDO::FETCH_ASSOC);
Your PDO statement is prepared every round inside the loop, that is not necessary and i hope the inbox_id column is a primary key in the inbox table: 您的PDO语句在循环内的每一轮都是准备的,这不是必须的,我希望inbox_id列是inbox表中的主键:
$stmt1 = $db->query("SELECT `inbox_id` FROM inbox ORDER BY `date` DESC ");
$stmt2 = $db->prepare("SELECT * FROM messages WHERE inbox_id=? AND seen=0 ORDER BY `date` DESC");
while($id = $stmt1->fetchColumn(0)) {
$stmt2->execute(array($id));
$row_msg[$id] = $stmt2->fetchAll(PDO::FETCH_ASSOC);
}
return $row_msg;
If you do not want a multidimensional array you can just add the row to the result array by using array_merge() ( PHP Manual: array_merge ) inside the loop (instead of the line with $row_msg[$id]): 如果您不希望使用多维数组,则可以通过在循环内(而不是带有$ row_msg [$ id]的行)使用array_merge()( PHP手册:array_merge )将行添加到结果数组中:
$row_msg = array_merge($row_msg, $stmt2->fetchAll(PDO::FETCH_ASSOC));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.