首页 > 解决方案 > 从数据库中检索行并存储到会话数组

问题描述

我正在尝试从数据库中检索行并将它们存储到数组/会话数组中(我有点迷茫)。我目前从中检索的数据库有 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();
?>

这是我到目前为止拼凑起来的,这样接近吗?任何指向正确方向的指针都将非常感谢。

标签: phphtmldatabase

解决方案


它很接近但不完全。检查示例

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
?>

推荐阅读