glutz
glutz

Reputation: 1959

Is it possible to hold a mysql object across sessions in php?

For example, in this case, the 'views' count is clearly incrementing properly during the session but the mysqli object is not maintained and cannot be reused during the session (if the page is refreshed or whatever). Can the _SESSION global only hold simple types? What else could be limiting this? EDIT: my hope here is to improve performance. So if there is another way to achieve this, I'd be happy to know.

<?php
session_start();

if(isset($_SESSION['db']))
{
    $mysqli = $_SESSION['db'];
    $_SESSION['views']=$_SESSION['views']+1;
}
else
{
    $mysqli = new mysqli(...);
    $_SESSION['db'] = $mysqli;
    $_SESSION['views']=1;
}

echo "Views=". $_SESSION['views'];    

?>

Upvotes: 1

Views: 161

Answers (2)

zerkms
zerkms

Reputation: 254944

Nope, none of php resources is serializable. So you need to instantiate mysqli object each time.

EDIT: my hope here is to improve performance.

The number one performance optimization rule is: first measure - second optimize. No one in the world can say what's the performance issue without profiling (measuring).

So, your application works unacceptable slow? Well, measure what makes it so slow and optimize that particular place. And I can assure you it's not the connection to mysql.

Upvotes: 3

mikespook
mikespook

Reputation: 796

You can't do this directly. But you could use magic methods: __sleep() and __wakeup().

class Connection {
    protected $link;
    private $server, $username, $password, $db;

    public function __construct($server, $username, $password, $db) {
        $this->server = $server;
        $this->username = $username;
        $this->password = $password;
        $this->db = $db;
        $this->connect();
    }

    private function connect() {
        $this->link = mysql_connect($this->server, $this->username, $this->password);
        mysql_select_db($this->db, $this->link);
    }

    public function __sleep() {
        return array('server', 'username', 'password', 'db');
    }

    public function __wakeup() {
        $this->connect();
    }
}

I don't think it's necessary doing so in with the session.

Upvotes: 0

Related Questions