如何从 PDO 将数据保存到 PHP 中的 cookie

How to save data into cookie in PHP from PDO

我需要一些帮助,因为我已经被困在这里一段时间了,作为一个菜鸟,请多多包涵,也许这对于经验丰富的开发人员来说可能很简单,基本上我正在尝试将数据保存到 cookie 中,这样我只点击数据库一次,之后,我想在重新加载页面时从 cookie 中获取数据,而不是再次点击数据库,我该如何实现?下面是我目前的代码

<?php

require_once("connection.php");

$sql = "select id,full_name,email,created_at from customers;";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

setcookie("customerList",serialize($result),time() + 3600,"/","",0);

try{
    if($stmt->rowCount() > 0){
        echo"<h1>List of Customers</h1>";
        echo"<table>";
           echo"<tr>";
                echo"<th>S/N</th>";
                echo"<th>Full Name</th>";
                echo"<th>Email Address</th>";
                echo"<th>Created At</th>";
                echo"<th>Action</th>";
           echo"</tr>";
           
           foreach($result as $row){
            echo"<tr>";
               echo"<td>{$row['id']}</td>";
               echo"<td>{$row['full_name']}</td>";
               echo"<td>{$row['email']}</td>";
               echo"<td>{$row['created_at']}</td>";
               echo"<td><input type='button' value='View'></td>";
            echo"</tr>"; 
           }
        echo"</table>";
        //free result
        unset($result);
    }else{
        echo "No records from your query were returned";
    }

}catch(PDOException $e){
    die("ERROR: Could not be able to execute $sql." . $e->getMessage());
}
//close
unset($pdo);

你可以:

  1. 检查cookie是否存在
  2. 如果为真,从中加载数据
  3. 如果为 false,从数据库加载数据并保存 cookie
  4. 循环显示结果

这是一个例子:

$cookieName = 'customerList';

// 1. check if cookie exists
if (! empty($_COOKIE[$cookieName])) {
    // 2. get cookie data
    $result = unserialize($_COOKIE[$cookieName]);
}
else {
    // 3. there is no cookie, load data from database
    $sql = "select id,full_name,email,created_at from customers;";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll();
    // save in cookie
    setcookie($cookieName, serialize($result),time() + 3600,"/","",0);
}

// 4. display result using $result only
if (!empty($result)) {
    echo"<h1>List of Customers</h1>";
    echo"<table>";
       echo"<tr>";
            echo"<th>S/N</th>";
            echo"<th>Full Name</th>";
            echo"<th>Email Address</th>";
            echo"<th>Created At</th>";
            echo"<th>Action</th>";
       echo"</tr>";
       
       foreach($result as $row){
        echo"<tr>";
           echo"<td>{$row['id']}</td>";
           echo"<td>{$row['full_name']}</td>";
           echo"<td>{$row['email']}</td>";
           echo"<td>{$row['created_at']}</td>";
           echo"<td><input type='button' value='View'></td>";
        echo"</tr>"; 
       }
    echo"</table>";
    //free result
    unset($result);
} else{
    echo "No records from your query were returned";
}