dtfpznrbn503027700 2018-05-04 01:34
浏览 47
已采纳

从数据库中检索行并存储到会话数组[重复]

This question already has an answer here:

I am trying to retrieve rows from a database and store them to an array/ session array (I am a bit lost). The database I am currently retrieving from has 3 rows.

<?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();
?>

This is what I have pieced together so far, is this close? Any pointers in the right direction would be great thanks.

</div>
  • 写回答

1条回答 默认 最新

  • dongxin5429 2018-05-04 01:49
    关注

    It's close but not quite. Check the examples at

    http://php.net/manual/en/mysqli.query.php and

    http://php.net/manual/en/mysqli-result.fetch-assoc.php and

    http://php.net/manual/en/mysqli-result.fetch-all.php

    Edits below.

    I would also consider looking up Binding variables instead of injecting session variables into a query. A malicious user could potentially set your $user_year variable and edit the query. More here: 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
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器