douchen4534 2012-06-28 00:19
浏览 32
已采纳

将PDO连接作为会话变量传递

So in the interest of not repeating myself, I only want to create one PDO connection and pass it between pages using a session var. But when I setup my PDO connection and set the session var, the var is coming back as not set on my next page?

This is the code on my first page:

session_start();
try
{
    $db = new PDO("mysql:host=".$dbHostname.";dbname=".$dbDatabase, $dbUsername, $dbPassword);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
    echo "It seems there was an error.  Please refresh your browser and try again. ".$e->getMessage();
}

$_SESSION['db'] = $db;

Then this test code on my next page comes back as not set.

session_start();
$db = $_SESSION['db'];

    if(isset($db))echo "set";
    else echo "not set";

Any ideas??

The connection is fine because if I call a function from the first page and pass along $db as a parameter, the function works without any problems. So why would storing the database var as a session not work? Thank you for any help.

  • 写回答

4条回答 默认 最新

  • dou47732 2012-06-28 00:25
    关注

    PDO does not allow session serialization. In fact, you should not be able to serialize database connections in the session at all. If it's really necessary to do that, you can do something like this:

    class DB {
       private $db;
       private $creds;
    
       public function __construct($host, $dbname, $user, $pass) {
          $this->creds = compact('host', 'dbname', 'user', 'pass');
          $this->db = self::createLink($host, $dbname, $user, $pass);
       }
    
       public function __sleep() {
          return array('creds');
       }
    
       public function __wakeup() {
          $this->db = self::createLink($this->creds['host'] ...
       }
    
       public static function createLink($host ...
          return new PDO(...
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器