所以,在mysql中你可以编写这样的嵌入式结构:
$query = mysql_query("SELECT `id` FROM `questions` WHERE `type`='foo';");
while($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$query2 = mysql_query("SELECT * FROM `answers` WHERE `question_id`='".$row['id']."'");
while($row2 = mysql_fetch_array($query2, MYSQL_ASSOC)) {
echo "Answer id:".$row2['id'];
}
}
是否可以使用prepare()在mysqli中执行此操作? 如果我写这个:
$mysqli = new mysqli(...);
$stmt = $mysqli->prepare("SELECT `id` FROM `questions` WHERE `type`=?;");
$stmt->bind_param('s','foo');
$stmt->execute();
$stmt->bind_result($question_id);
while ($stmt->fetch()) {
$stmt2 = $mysqli->prepare("SELECT * FROM `answers` WHERE `question_id`=?");
die(var_dump($stmt2)); // bool(false)
}
$ stmt2是布尔值false,因为我没有关闭$ stmt。但如果我关闭它,我就无法在循环中访问结果数据。那么,唯一的方法 - 将$ stmt的结果复制到另一个变量,执行$ stmt-> close()然后启动while()循环? 或者有其他方法可以做到这一点?
或者我不明白......:)
感谢您的回答!
答案 0 :(得分:0)
使用问题主键的联接和排序:
$stmt = $mysql->prepare("SELECT q.*, a.* FROM questions q LEFT JOIN answers a ON (q.id = a.question_id) WHERE q.type = ? ORDER BY q.id");
$stmt->bind_param('s','foo');
$stmt->execute();
$stmt->bind_result($question_id);
$currentQuestion = false;
while ($stmt->fetch()) {
if($currentQuestion !== $question_id){
$currentQuestion = $question_id;
// output question or whatever
}
// output answers
}
你必须要小心谨慎的是,如果要返回一个关联数组,那么如果表共享列(例如两个表可能都有id
列)那么你只会得到一个价值。要避免这种情况,您需要为列添加别名,这意味着您必须在查询中将它们全部替换为ALL:
SELECT q.id as qid, q.body as qbody, q.type as qtype, a.id as aid, a.body as abody, a.question_id as aqid FROM questions q LEFT JOIN answers a ON (q.id = a.question_id) WHERE q.type = ? ORDER BY qid