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.

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.