Jump to content

Recommended Posts

Hi, I have created a small class, that initiates a mysqli connection within it and stores it as an object.

 

the class works fine untill I try to store it in a session and pass it to a new page.

I define the class before I call session start, and the class in itself gets copied across, its just the mysqli connection that doesn't.

 

I get the error

Warning: mysqli::query() [mysqli.query]: Couldn't fetch mysqli

Warning: users::getUserInformation() [users.getuserinformation]: Couldn't fetch mysqli 

var_dump of class object
object(users)#1 (5) { ["user:private"]=> string(3) "tom" ["user_id:private"]=> string(1) "1" ["password:private"]=> NULL ["db_connection:private"]=> object(mysqli)#2 (0) { } ["errors:private"]=> array(1) { [0]=> string(117) "getUserInformation() :: Database Connection Fail 
select * from database.users WHERE UserID = '1' 
" } }

Link to comment
https://forums.phpfreaks.com/topic/174636-object-via-session/
Share on other sites

A database connection is a resource and they don't persist between pages, even if saved in a session.

 

And even if you were using a persistent database connection, you would not save it and reuse it on a different page. You would get or create one of the available persistent connections on each page.

Link to comment
https://forums.phpfreaks.com/topic/174636-object-via-session/#findComment-920352
Share on other sites

make sure you include the page where your class is defined before session_start() also. post the relevent code.

 

also what exactly is your problem? is your class not being transfered between pages, or is it a different proglem

 

the class is going but in the class I create a mysqli object and store it in a variable within the class

heres my class

<?php
class users {
    
    private $user;
    private $user_id;
    private $password;

    private $db_connection;
    private $errors;

    function initiate_connection(){
        $this->db_connection = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DATABASE);
    }

    function getLiveDatabaseConnection(){
        if(!is_object($this->db_connection)){
            $this->initiate_connection();
            return $this->db_connection;
        }else {
            return $this->db_connection;
        }
        
    }

    function setUserName($username){
        $this->user = $username;
        return $this;
    }

    function setPassword($password){
        $this->password = $password;
        return $this;
    }

    function setUserID($uid){
        $this->user_id = $uid;
        return $this;
    }
    
    function getUserInformation(){
        if(isset($this->user_id)){
            $uid = $this->user_id;
        } else {
            $this->errors[] = "getUserInformation() :: No User ID Set";
            return false;
        }
        $sql = "select * from berserke_Rogue.users WHERE UserID = '$uid'";
        $mysql = $this->getLiveDatabaseConnection();
        $result = $mysql->query($sql);
        if(!$result){
            $this->errors[] = "getUserInformation() :: Database Connection Fail <br /> $sql <br /> {$this->db_connection->error}";
            return false;
        } else {
            $row = $result->fetch_assoc();
            echo $row['UserName']." ".$row['UserPass'];
        }
    }
    
    function ShowErrors(){
        if(is_array($this->errors)){
            foreach ($this->errors as $error){
                echo $error."<br />";
            } 
        } else {
            echo $this->errors;
        }
            
    }
}
?>

 

I have altered it abit since my original draft but this is jist of it.

 

on page one I would do

<?php
    session_start();

    require_once('phpclasses/class_users.php');

    $user = new users();
    $user->setUserName("tom")->setUserID("1");
    $user->getUserInformation();
    
    //Set Session Variables
    $_SESSION['oUser'] = serialize($user);
    
     var_dump($user);
?>

the var_dump for this page

object(users)#1 (5) { ["user:private"]=> string(3) "tom" ["user_id:private"]=> string(1) "1" ["password:private"]=> NULL ["db_connection:private"]=> object(mysqli)#2 (0) { } ["errors:private"]=> NULL }

 

page 2 goes like this

<?php
require_once('phpclasses/class_users.php');
session_start();
$user = unserialize($_SESSION['oUser']);
$user->getUserInformation();
var_dump($user);
?>

 

the var dump and error code is

Warning: mysqli::query() [mysqli.query]: Couldn't fetch mysqli

Warning: users::getUserInformation() [users.getuserinformation]: Couldn't fetch mysqli 
object(users)#1 (5) { ["user:private"]=> string(3) "tom" ["user_id:private"]=> string(1) "1" ["password:private"]=> NULL ["db_connection:private"]=> object(mysqli)#2 (0) { } ["errors:private"]=> array(1) { [0]=> string(117) "getUserInformation() :: Database Connection Fail 
select * from berserke_Rogue.users WHERE UserID = '1' 
" } }

Link to comment
https://forums.phpfreaks.com/topic/174636-object-via-session/#findComment-920353
Share on other sites

A database connection is a resource and they cannot be saved in a session.

 

ahh that explains that, is there a way to limit the amount of connections used, it's hard to explain what I am trying to do I am trying to cut down the database connections made to one per users by giving them a connection when they log in and anything that requires that requires a db connection can be done using the one stored in their session rather than creating a new one when they need it etc.

Link to comment
https://forums.phpfreaks.com/topic/174636-object-via-session/#findComment-920354
Share on other sites

A database connection is destroyed when the script on any page ends.

This is not necessarily true. As far as I know, something called persistent connections exist.

 

Anyway. A possible solution might be using the __wakeup() magic method to reestablish database connection when the users object is unserialized.

Link to comment
https://forums.phpfreaks.com/topic/174636-object-via-session/#findComment-920360
Share on other sites

Persistent database connections only work on a limited list of web servers and only when php is running as a server module.

 

SetToLoki, what makes you think that a single user is taking up more than one database connection now? What exact problem or error are you getting that you are trying to solve?

Link to comment
https://forums.phpfreaks.com/topic/174636-object-via-session/#findComment-920367
Share on other sites

Persistent database connections only work on a limited list of web servers and only when php is running as a server module.

 

SetToLoki, what makes you think that a single user is taking up more than one database connection now? What exact problem or error are you getting that you are trying to solve?

 

no problems, just keep forgetting to close connections etc, wanted a tidier system so thought I might use sessions so I could follow what connections are being made, as I used multiple classes all of which make database connections at different time for different reasons so wanted to make some system that means when a connection is required it would use an open one or open a new one if none exists rather than just creating a new one regardless of an open unused (probably because some messy code forgot to close it), I thought about making a class that just manages the database connections all other classes that connect to the database do so through this class.

 

if that makes sense - I sort of know what I am after but struggle to put it into words

Link to comment
https://forums.phpfreaks.com/topic/174636-object-via-session/#findComment-920372
Share on other sites

  • 4 months later...

I am going to bring this one back from the dead since I think it is an interesting and valid question.  I have a question of my own about how to handle this stuff though.

 

I had previously worked on some Perl/CGI stuff about 5 years ago in an internship.  It used a MySQL backend and what we found was that we were constantly opening and closing handles to the database -- which caused a severe performance hit.  So we eventually defined two new functions:

 

1. db_connect() -- connects to the database

2. get_db_handle() -- if the dbh == -1 then we call db_connect() and return the handle.  Else we simply return the handle already stored

 

 

This sped up performance SIGNIFICANTLY in the application.  One page was drastically reduced from like 26 seconds to fully load to about 2 seconds.  Granted, these database connections were being constantly created and torn down within a loop (i.e. code in the same file...the same function even).  So it is a bit different to PHP which is only tearing down the connection when the user navigates to another page.  I guess as long as your users aren't sitting there constantly between PHP pages, your code should be more than responsive.

 

I still have the following question though:

 

1. What is the best way to maintain database connections.  Should I just copy and paste the same mysql_connect() code into every PHP page that I write?  I was thinking about defining two functions like I discussed above...one to get the db connection and another to create it (if it doesn't exist).  Then, whenever I need the db connection in my code I can just do something like:

 

$con = getDBConnection();

 

Instead of typing code like this over and over again:

 

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="topsecret!"; // Mysql password

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");

 

 

Is that the preferred way to handle this?  Clearly typing out multiple lines of code again and again is much more error prone than typing a single line.  I am just trying to figure out the good "rule of thumb" type stuff for MySQL connections in my PHP code.  Thanks!

Link to comment
https://forums.phpfreaks.com/topic/174636-object-via-session/#findComment-1000910
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.