Posts Tagged ‘Database’:


Database Abstraction

When using MySQL in PHP I often use a simple database abstraction class that I wrote some time ago. This class sits as a layer between the application and database layers. I find that this really shortens the amount of code I have to write. The result is a more organic, succinct script. At this stage the class only has three main abstraction methods:

Database::fetchAll( $sql ); Database::fetchAssoc( $sql ); Database::query( $sql );
									

Example usage would be as follows:

// You'd probably wanna put this in a constructor somewhere or something like that....
Database::conect();

$sql = "SELECT * FROM `users`";
$result = Database::fetchAssoc( $sql );

// Loop through the results and print each user's first name
foreach( $users as $user ){
    print $user['first_name'];
}

// Like connect, you might want to put this is a destructor...
Database::close();
									

You can download the class from my GitHub repo at https://github.com/mikedhart/Database-Abstraction

Tags: , ,
-->
© Mike Hart