A basic pdo database class

griimnak

You're a slave to the money then you die
Jul 20, 2013
955
794
As you may know, mysql is depreciated in the latest php release.
You could use mysqli but i prefer pdo. this is a database class that I use on my personal site:

database.php:
PHP:
class Database {
   
    public static function dbConnect() {

        global $config;

        try {

            $username =  $config['db']['user'];
            $password = $config['db']['pass'];
            $dbb = $config['db']['database'];
            $hostname = $config['db']['host'];
            $conn = new pdo("mysql:host=$hostname;dbname=$dbb;", $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $conn;

            }   catch(PDOException $e) {

            $dberror = '<b style="text-color: red;"> Output a custom error with style </b>';
            die($dberror);
           
        }
    }
}

config.php:

PHP:
$config['db']['host'] = 'localhost';
$config['db']['user'] = 'root';
$config['db']['pass'] = 'pass';
$config['db']['database'] = 'db';

finally, the usage
index.php:

PHP:
require_once 'config.php';
require_once 'database.php';

$query = Database::dbConnect()->prepare("SELECT * FROM sometable");
$query->execute();
$result = $query->fetchAll();

foreach($result as $row) {
                  
          $certain_row = $row['username'];

}

if($certain_row == 'griimnak'){

        echo 'hi griimnak';

}

it's simple and gets the job done. Keep in mind php isn't my best language, but this is good base for you to build upon.
 

SeanRog

Member
Jul 24, 2010
51
10
Really? Are you really going to connect to the Database for every query you run?

Oh jesus, I see HTML tags echo'd out.
 

Khalil

IDK
Dec 6, 2011
1,642
786
I know you call this basic, but this could really use more work, in fact, I wouldn't call this a base at all, it lacks a lot of essential functionalities for it to even be a base. However, it could come in handy to noobs who are still in their learning phase. Much obliged for the effort.
 

griimnak

You're a slave to the money then you die
Jul 20, 2013
955
794
Really? Are you really going to connect to the Database for every query you run?

Oh jesus, I see HTML tags echo'd out.
I guess, i mean, isn't that better then having a persistent connection? just diconnect the shit when you don't need it? idk
and about the tags, suck my nuts
The fact you think you know all, shows that you still know nothing.

ON TOPIC: I know you call this basic, but this could really use more work, in fact, I wouldn't call this a base at all, it lacks a lot of essential functionalities for it to even be a base. However, it could come in handy to noobs who are still in their learning phase. Much obliged for the effort.
Thanks, and yeah man I agree. looking back to this, this was realy bare bone. Perhaps i'll write a proper pdo db class when I have some time
 

DarkStar851

New Member
Jan 11, 2013
4
5
Store the connection in a variable after it's been instantiated once and call your queries against that instance. This is just... stop.
People seriously need to stop reinventing the fucking wheel. Just search "mysql" on Packagist, there are over four hundred indexed packages for dealing with databases. aura/sql is pretty solid imo.
 

SeanRog

Member
Jul 24, 2010
51
10
Use the same connection trough out the script.

Take my database handler as an example:
Code:
/**
* @var Database\Connection
*/
private static $connection;

/**
* @return Database\Connection
*/
public static function GetConnection()
{
    if(is_null(self::$connection))
    {

        // Connect to database
        $credentials = \App\Config\Database::GetAll();
        self::$connection = new Database\Connection(
            $credentials['dsn'],
            $credentials['username'],
            $credentials['password'],
            isset($credentials['options'])?$credentials['options']:null
        );

        // Set exceptions error mode
        self::$connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

    }

    return self::$connection;
}
 

griimnak

You're a slave to the money then you die
Jul 20, 2013
955
794
Use the same connection trough out the script.

Take my database handler as an example:
Code:
/**
* @var Database\Connection
*/
private static $connection;

/**
* @return Database\Connection
*/
public static function GetConnection()
{
    if(is_null(self::$connection))
    {

        // Connect to database
        $credentials = \App\Config\Database::GetAll();
        self::$connection = new Database\Connection(
            $credentials['dsn'],
            $credentials['username'],
            $credentials['password'],
            isset($credentials['options'])?$credentials['options']:null
        );

        // Set exceptions error mode
        self::$connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

    }

    return self::$connection;
}
That looks pretty nice!
 

Weasel

👄 I'd intercept me
Nov 25, 2011
4,128
2,456
Use the same connection trough out the script.

Take my database handler as an example:
Code:
/**
* @var Database\Connection
*/
private static $connection;

/**
* @return Database\Connection
*/
public static function GetConnection()
{
    if(is_null(self::$connection))
    {

        // Connect to database
        $credentials = \App\Config\Database::GetAll();
        self::$connection = new Database\Connection(
            $credentials['dsn'],
            $credentials['username'],
            $credentials['password'],
            isset($credentials['options'])?$credentials['options']:null
        );

        // Set exceptions error mode
        self::$connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

    }

    return self::$connection;
}
Does mr. self-proclaimed Senpai know functions within classes need camelCasing?
 

griimnak

You're a slave to the money then you die
Jul 20, 2013
955
794
I've always wondered why php programmers code like this:

PHP:
class class
{
     public function function()
     {
              echo 'hi'
     }
}

So fucking ugly (IMO), this looks much prettier to me:

PHP:
class class {
     public function function() {
          echo 'hi'
     }
}
 

Weasel

👄 I'd intercept me
Nov 25, 2011
4,128
2,456
I've always wondered why php programmers code like this:

PHP:
class class
{
     public function function()
     {
              echo 'hi'
     }
}

So fucking ugly (IMO), this looks much prettier to me:

PHP:
class class {
     public function function() {
          echo 'hi'
     }
}
Everyone has their own preference, there is no specific rule (coding standard) which says you MUST have the opening bracket on the same line as the function/class, however they do say you SHOULD do it. I always try to follow the PHP coding standards, however I do prefer the bracket on the next line myself. Especially in long if statements, it's easier to read/oversee the code.
 

SeanRog

Member
Jul 24, 2010
51
10
Does mr. self-proclaimed Senpai know functions within classes need camelCasing?

camelCasing public static functions? :-(

I don't camelCase rather PascalCase static functions because I think
Class::FunctionName();
looks better than
Class::functionName();

But in OO classes I camelCase
 
Last edited:

Users who are viewing this thread

Top