Jump to content

best way to store database (w/ abstraction layer like MDB2) in session code


arianhojat

Recommended Posts

I want to store database connection in session so dont need to reconnect to database on each page but wasnt sure what is best way to do this.

 

My 1st impluse is in my php/session code, is to do something like this:

 

<?php
//On session page
session_start(); //needed

require_once 'MDB2.php';

if(!$_SESSION['uid'])//session not set, get users info and set it in session
{

$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'password';
$db_name = 'mysql';
$dsn = "mysql://$db_user:$db_pass@unix+$db_host/$db_name";
$mdb2 =& MDB2::connect($dsn);

if( !(PEAR::isError($mdb2) )//test a query to generic mysql database just to test if connected
{		
	$_SESSION['dbAbstract'] = serialize( $dbAbstract );
}


$_SESSION['uid'] = $_SERVER["AUTH_USER"];
}



//On php page

require_once 'MDB2.php';
include 'session.php';

$dbAbstract = unserialize( $_SESSION['dbAbstract'] );

$testsql = 'SELECT * FROM mysql.help_category';	
$result =& $mdb2->query($testsql);

if( PEAR::isError($result) )
{
	echo "<br />Search error...";
    die($result->getMessage());
}
?>

 

 

But what if loses connection, even though session is still alive.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.