Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you manage database connections in php?

So recently I've really started to use php actively, and I need some insights on different ways to use database connections.

At first I just used the simple mysql_connect():

<?php
    $connection = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());
    mysql_select_db(DB_DB, $connection);
?>

After a while I created a database class which I started to include and initialize in every file - something like this:

<?php
class MySQL_DB {

var $connection;

function MySQL_DB(){
    $this->connection = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());
    mysql_select_db(DB_DB, $this->connection);
}

function query($q){
    $res = mysql_query($q, $this->connection) or die(mysql_error());
    return $res;
}
}

$database = New MySQL_DB;
?>

And this is what I'm using at the time - and it's working fine - but there are always ways to improve.

So my question to you is how do you manage your database connections?

  • Do you use classes?
  • What does your classes contain (just the connection or even functions?)
  • What practices do you recommend?
like image 469
Fifth-Edition Avatar asked Oct 16 '09 22:10

Fifth-Edition


People also ask

How can I connect online database in PHP?

Open your browser and go to localhost/PHPMyAdmin or click “Admin” in XAMPP UI. Now click Edit privileges and go to Change Admin password, type your password there and save it. Remember this password as it will be used to connect to your Database.


1 Answers

I recommend to use PDO. Don't reinvent the weel. It's a nice OO-interface to many database engines. Additionally I create a small function which just inititializes PDO object. So all connection settings can be changed in one place.

like image 61
Ivan Nevostruev Avatar answered Sep 26 '22 21:09

Ivan Nevostruev