使用 php 从数据库中获取多维数组时出错
Error in fetching multidimensional array from database using php
有一项数据库考试有 table 考试。
我想 运行 存储在 $sql_query
中的查询。
它在本地主机 SQL 服务器中显示的输出是:
但是在 php 中使用它时它只显示单行。
$sql_query = "SELECT * FROM exam_timing AS et INNER JOIN exam_details AS ed
ON et.exam_id = ed.Id WHERE et.Admin_Id = '$username'";
$ids = mysqli_fetch_array(mysqli_query($db_exams, $sql_query), MYSQLI_NUM);
foreach($ids as $id) {
echo $id," ";
}
这个输出是:
27 113 15:59:00 2020-12-25 30 2 pb 113 php BCA 2 1
它应该显示两行。
mysqli_fetch_array
只取结果的first row作为数组,自增结果集行指针
使用函数mysqli_fetch_all
$ids = mysqli_fetch_all(mysqli_query($db_exams, $sql_query), MYSQLI_NUM);
有关 mysqli_fetch_all here
的更多详细信息
问题
- 您需要用参数替换查询中的每个变量,稍后绑定变量
- 获取结果的方式
- 您只获取第一个结果行
- 您的循环遍历列而不是结果集
解决方案
// SQL statement
$sql = "
SELECT *
FROM exam_timing AS et
INNER JOIN exam_details AS ed
ON et.exam_id = ed.Id
WHERE et.Admin_Id = ?
";
$query = $mysqli->prepare($sql); // Prepare the query
$query->bind_param("s", $username); // `s` because you're variable was $username and I've assumed string; use `i` if it's an integer id
$query->execute(); // Run the query
$result = $query->get_result(); // Get the result set from the database
// Loop through returned result sets
while( $row = $result->fetch_assoc() ){
// Loop through the columns in the row
foreach($row as $column){
echo $column, ' ';
}
echo "\n";
}
/* Output:
27 113 15:59:00 2020-12-25 30 2 pb 113 php BCA 2 1
28 114 16:32:00 2021-01-09 23 2 pb 114 php BCA 3 7
*/
有一项数据库考试有 table 考试。
我想 运行 存储在 $sql_query
中的查询。
它在本地主机 SQL 服务器中显示的输出是:
但是在 php 中使用它时它只显示单行。
$sql_query = "SELECT * FROM exam_timing AS et INNER JOIN exam_details AS ed
ON et.exam_id = ed.Id WHERE et.Admin_Id = '$username'";
$ids = mysqli_fetch_array(mysqli_query($db_exams, $sql_query), MYSQLI_NUM);
foreach($ids as $id) {
echo $id," ";
}
这个输出是:
27 113 15:59:00 2020-12-25 30 2 pb 113 php BCA 2 1
它应该显示两行。
mysqli_fetch_array
只取结果的first row作为数组,自增结果集行指针
使用函数mysqli_fetch_all
$ids = mysqli_fetch_all(mysqli_query($db_exams, $sql_query), MYSQLI_NUM);
有关 mysqli_fetch_all here
的更多详细信息问题
- 您需要用参数替换查询中的每个变量,稍后绑定变量
- 获取结果的方式
- 您只获取第一个结果行
- 您的循环遍历列而不是结果集
解决方案
// SQL statement
$sql = "
SELECT *
FROM exam_timing AS et
INNER JOIN exam_details AS ed
ON et.exam_id = ed.Id
WHERE et.Admin_Id = ?
";
$query = $mysqli->prepare($sql); // Prepare the query
$query->bind_param("s", $username); // `s` because you're variable was $username and I've assumed string; use `i` if it's an integer id
$query->execute(); // Run the query
$result = $query->get_result(); // Get the result set from the database
// Loop through returned result sets
while( $row = $result->fetch_assoc() ){
// Loop through the columns in the row
foreach($row as $column){
echo $column, ' ';
}
echo "\n";
}
/* Output:
27 113 15:59:00 2020-12-25 30 2 pb 113 php BCA 2 1
28 114 16:32:00 2021-01-09 23 2 pb 114 php BCA 3 7
*/