php - 从数据库中检索行并存储到会话数组
问题描述
我正在尝试从数据库中检索行并将它们存储到数组/会话数组中(我有点迷茫)。我目前从中检索的数据库有 3 行。
<?php
session_start();
$user_year = $_SESSION['year'];
$floor = $_SESSION['year_floor'];
include "config.php";
$query = "select * from timetable where '$user_year' = year;
$array = array();
while($row = $query->fetch_assoc()){
$array[] = $row;
}
echo '<script>console.log(\"$array\")</script>';
/* close connection */
// debug:
print_r($array); // show all array data
echo $array[0]['username']; // print the first rows username
$mysqli->close();
?>
这是我到目前为止拼凑起来的,这样接近吗?任何指向正确方向的指针都将非常感谢。
解决方案
它很接近但不完全。检查示例
http://php.net/manual/en/mysqli.query.php和
http://php.net/manual/en/mysqli-result.fetch-assoc.php和
http://php.net/manual/en/mysqli-result.fetch-all.php
下面进行编辑。
我还会考虑查找绑定变量而不是将会话变量注入查询。恶意用户可能会设置您的 $user_year 变量并编辑查询。更多信息:http: //php.net/manual/en/mysqli-stmt.bind-param.php
<?php
session_start();
$user_year = $_SESSION['year'];
$floor = $_SESSION['year_floor'];
include "config.php"; //I assume you create a $mysqli object here
$query = "select * from timetable where year = '$user_year'";
$results_array = array(); // I try to avoid using variable types as names so have renamed to results_array
$result = $mysqli->query($query); // mysqli runs the query (see man above)
//The result runs the fetch_assoc (see man above)
while($row = $result->fetch_assoc()){
$result_array[] = $row;
}
// If you know you have a small result set you could replace the while() loop above with $result_array = $result->fetch_all()
// echo '<script>console.log(\"$array\")</script>'; (this wont work because the client side javascript can't understand the php variable. But you could place this line inside the loop above.)
// debug:
print_r($result_array); // show all array data
echo $result_array[0]['username']; // print the first rows username
$mysqli->close(); // you don't need to do this unless saving memory mid script, but it's good practice so I left it in
?>
推荐阅读
- c# - 如何让 WCF 服务使用 HTTPS 协议
- c# - 将嵌套的 JSON 转换为字典
- woocommerce - 我如何在 Woocommerce 中仅对登录用户应用折扣?
- c - 堆栈帧上缺少注入字符串的某些部分
- javascript - Typescript:Getter 无法返回自定义类型的数组
- c# - 如何说服 Refit 不要添加 xml 序言?
- rest - 确保在后台处理 Flutter 应用程序中的 REST 调用
- swift - 在这种情况下,如何重用 UIPickerView 中的视图?
- python - 将整列附加到字典中
- python - 在将函数应用于 numpy 数组的每一行时,如何返回 numpy 数组而不是 NoneType?