【问题标题】:How to select multiple records from SQL and insert into a Session如何从 SQL 中选择多条记录并插入到会话中
【发布时间】:2016-02-19 05:14:02
【问题描述】:

我正在寻找如何将 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;   

“课程”表里面有几条记录,所有的teacherID都是当前用户ID的记录,在开始时定义。当我 print_r($_SESSION['courseinfo']);它只显示表中的一条记录。

我正在尝试创建一个循环来显示每条记录的所有抓取信息,因为您无法确定在任何给定时间您将抓取多少条记录。任何答案都非常感谢!

【问题讨论】:

  • 你可以使用 fetchAll() 来返回一个包含所有行的数组!

标签: php mysql session session-variables multiple-select


【解决方案1】:
$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;

使用 while() 循环根据您的查询获取所有记录

【讨论】:

    【解决方案2】:

    您可以通过更改 fetch 来获取所有记录 -> fetchAll() doc

    $rows = $stmt->fetchAll(); 
    

    会话还可以存储数组和对象(它们会自动序列化)。因此,您可以将整个结果集存储在那里。

    $_SESSION['courseinfo'] = $rows;
    

    旁注:考虑为所有返回的数据使用另一个存储位置,如果它很多,并且在会话中仅存储 ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 2012-05-26
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多