theboy
theboy

Reputation: 60

avoid multiple mysqli connection with db class

i just started oop and now, even very simple things seem confusing to me! this is my class for mysqli connection:

class DB{
    private $con;
    public function __construct(){
        $this->con=new mysqli('localhost','root','','dbName');
        if(!$this->con){
            echo '<b>There was a problem connecting to database! </b><br />errno: '.$con->connect_errno;
            exit;
        }
        $this->con->set_charset("utf8");
    }
    public function query($query){
        return $this->con->query($query);
    }
}

let's say i'm gonna use that like this:

$a=mysqli_real_escape_string($_POST['a']);
$b=mysqli_real_escape_string($_POST['b']);

$query='SELECT `name` FROM `someTable` WHERE `type`={'.$a.'}';
$query2='SELECT `name` FROM `someTable` WHERE `type`={'.$b.'}';

$DB = NEW DB;
$test=$DB->query($query);

$DB2 = NEW DB;
$test2=$DB2->query($query2);

i just created 2 objects from class DB. does it mean there is a new mysql connection for each object? if yes, how can i avoid it?

i know i can use mysqli_close() in __destruct() function but i read somewhere (probably in this very site :) ) that creating and destroying several mysql connections isn't good.

what should i do? p.s: beside, just as i said i'm new in oop (and mysqli as well) so if there is any comment about my class (for example did i set the charset at the right place?) i'll be honored.

Upvotes: 0

Views: 1110

Answers (1)

ICE
ICE

Reputation: 1737

When you are creating an instance of a class, you don't need to recreate it if it works properly.

Example 1

in your question you did this:

$DB = new DB();
$test=$DB->query($query);

$DB2 = new DB();
$test2=$DB2->query($query2);

You can do this instead:

$DB = new DB();
$test = $DB->query($query);
$test2 = $DB->query($query2);

Example 2

Sometimes you have an instance and you want to use it everywhere. you can create it at the start of your code or at the first request. and then you can use it everywhere.

$DB = new DB();

function something(){

    global $DB;

    $test = $DB->query($query);
}

If your class is simple as you mentioned here, just use it like the first example. This method is for an instance that need to access from everywhere. one function change something in it and another function using that change.

Also this method consider as bad practice because it makes your code much harder to read and debug.

Some useful links:

Upvotes: 1

Related Questions