感谢到目前为止的贡献 - 我现在可以看到$ rowq不是单个数组但是很多 - 我想将所有行带回数组中,有什么建议吗?
首先,将我的数据带回数组的代码:
function fetch_questions($page) {
global $link;
$proc = mysqli_prepare($link, "SELECT * FROM tques WHERE page = ?");
mysqli_stmt_bind_param($proc, "i", $page);
mysqli_stmt_execute($proc);
$rowq = array();
stmt_bind_assoc($proc, $rowq);
// loop through all result rows
while ($proc->fetch()) {
// print_r($rowq);
}
mysqli_stmt_close($proc);
mysqli_clean_connection($link);
return($rowq);
}
现在,当我'print_r($ rowq);'我得到以下内容,这一切都很好:
Array ( [questions] => q1 [qnum] => 1 [qtext] => I find my job meaningful [page] => 1 ) Array ( [questions] => q2 [qnum] => 2 [qtext] => I find my job interesting [page] => 1 ) Array ( [questions] => q3 [qnum] => 3 [qtext] => My work supports ABC's objective [page] => 1 ) Array ( [questions] => q4 [qnum] => 4 [qtext] => I am able to balance my work and home life [page] => 1 ) Array ( [questions] => q5 [qnum] => 5 [qtext] => I am clear about what is expected of me in my job [page] => 1 ) Array ( [questions] => q6 [qnum] => 6 [qtext] => My induction helped me to settle into my job [page] => 1 ) Array ( [questions] => q7 [qnum] => 7 [qtext] => I understand the ABC vision [page] => 1 ) Array ( [questions] => q8 [qnum] => 8 [qtext] => I know how what I do fits into my team's objectives [page] => 1 )
现在,在我的php页面中,我有以下脚本:
$questions = fetch_questions($page);
当我print_r $问题时,如下所示:
print_r($questions);
我只从阵列中获得以下内容,1行:
Array ( [questions] => q8 [qnum] => 8 [qtext] => I know how what I do fits into my team's objectives [page] => 1 )
为什么会有这样的想法?
提前致谢,
荷马。
答案 0 :(得分:3)
您没有在数组中收集结果。您print_r
循环中的每一行都是while
。
因此,如果仔细查看显示的结果,实际情况就是这样:
// in each iteration of the while loop
// print_r( $rowq )
Array ( [questions] => q1 [qnum] => 1 [qtext] => I find my job meaningful [page] => 1 )
// print_r( $rowq )
Array ( [questions] => q2 [qnum] => 2 [qtext] => I find my job interesting [page] => 1 )
// print_r( $rowq )
Array ( [questions] => q3 [qnum] => 3 [qtext] => My work supports ABC's objective [page] => 1 )
// etc..
它只是在彼此身后出现。
因此,在调用函数时,您只是从while循环返回最后一行。
作为旁注:
您没有按预期使用mysqli_prepare
。您应该将$page
替换为?占位符,如下:
$proc = mysqli_prepare($link, "SELECT * FROM tques WHERE page = ?");
// the following statement will properly replace the placeholder with $page
mysqli_stmt_bind_param($proc, "i", $page);
答案 1 :(得分:3)
您的$rowq
变量只保存最后一行。在获取循环期间print_r
时,每行都会被提取到$rowq
变量中,然后立即打印,但因为每次迭代都会覆盖变量,当循环完成时,只包含最后一行$rowq
。
如果要挂起所有行,可以增强功能:
function fetch_questions($page) {
// ...
$rows = array();
while ($proc->fetch()) {
$rows[] = $rowq;
}
// ...
return $rows;
}
使用此代码(仅包含相关部分),每次获取一行时,它都放在一个数组$rows
中,当循环完成时,该数组包含所有行