简体   繁体   English

如何从SQL中选择多个记录并插入到Session中

[英]How to select multiple records from SQL and insert into a Session

I am looking for how to insert multiple records from a SQL table into a session variable, or into multiple unique session variables. 我正在寻找如何将SQL表中的多个记录插入到会话变量或多个唯一会话变量中。

$userID = $_SESSION['user']['id']; 

$coursequery = " 
            SELECT
                coursename,
                location,
                description 
            FROM courses 
            WHERE 
                teacherID = '$userID' 
        "; 

        try 
        { 
            $stmt = $db->prepare($coursequery); 
            $result = $stmt->execute(); 
        } 
        catch(PDOException $ex) 
        {  
            die("Failed to run query: " . $ex->getMessage()); 
        } 

        $row = $stmt->fetch(); 

            $_SESSION['courseinfo'] = $row;   

The table "courses" has a few records inside, all with the teacherID being that of the current userID, defined at the start. 表“courses”里面有一些记录,所有记录都是在开始时定义的当前userID的内容。 When I print_r($_SESSION['courseinfo']); 当我print_r($ _ SESSION ['courseinfo']); it only displays one of the records in the table. 它只显示表中的一条记录。

I'm trying to create a loop that displays all the information grabbed, for each record, since you won't know for sure how many records you'll grab at any given time. 我正在尝试为每条记录创建一个显示所有抓取信息的循环,因为您无法确定在任何给定时间内您将获取多少条记录。 Any answers are greatly appreciated! 任何答案都非常感谢!

$userID = $_SESSION['user']['id']; 

$coursequery = " 
            SELECT
                coursename,
                location,
                description 
            FROM courses 
            WHERE 
                teacherID = '$userID' 
        "; 

        try 
        { 
            $stmt = $db->prepare($coursequery); 
            $result = $stmt->execute(); 
        } 
        catch(PDOException $ex) 
        {  
            die("Failed to run query: " . $ex->getMessage()); 
        } 

        while ($row = $stmt->fetch()):

         $row['YourColumn'];

         endwhile;

Use while() loop to fetch all record as per your query 使用while()循环根据您的查询获取所有记录

You can fetch all your records with changing the fetch -> fetchAll() doc 您可以通过更改fetch - > fetchAll() doc来获取所有记录

$rows = $stmt->fetchAll(); 

Sessions can also store arrays and objects (they get serialized automatically). 会话还可以存储数组和对象(它们会自动序列化)。 So you can just store the whole results set there. 所以你可以在那里存储整个结果集。

$_SESSION['courseinfo'] = $rows;

Side note: Consider using another storage place for all of the returned data, if its a lot, and in the session store only Ids. 附注:考虑为所有返回的数据使用另一个存储位置(如果很多),并且在会话存储中仅使用ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM