从数据库中检索行并存储到会话数组

时间:2018-05-04 01:34:51

标签: php html database

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

这是我到目前为止拼凑的内容,这是否接近? 任何正确方向的指针都会非常感谢。

1 个答案:

答案 0 :(得分:0)

它很接近但不完全。查看

上的示例

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
?>
相关问题