Super-Fast PHP Mysql Database Class: Source
Super-Fast PHP Mysql Database Class: Source
This lightweight database class is written with PHP and uses the MySQLi extension, it uses prepared statements to
properly secure your queries, no need to worry about SQL injection attacks.
The MySQLi extension has built-in prepared statements that you can work with, this will prevent SQL injection and
prevent your database from being exposed, some developers are confused on how to use these methods correctly so
I've created this easy to use database class that'll do the work for you.
This database class is beginner-friendly and easy to implement, with the native MySQLi methods you need to write 3-7
lines of code to retrieve data from a database, with this class you can do it with just 1-2 lines of code, and is much
easier to understand.
Source
PHPCopy
<?php
class db {
protected $connection;
protected $query;
protected $show_errors = TRUE;
protected $query_closed = TRUE;
public $query_count = 0;
public function __construct($dbhost = 'localhost', $dbuser = 'root', $dbpass = '', $dbname = '',
$charset = 'utf8') {
$this->connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($this->connection->connect_error) {
$this->error('Failed to connect to MySQL - ' . $this->connection->connect_error);
}
$this->connection->set_charset($charset);
}
}
?>
How To Use
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'example';
$account = $db->query('SELECT * FROM accounts WHERE username = ? AND password = ?', array('test', 'test'))-
>fetchArray();
echo $account['name'];
You can specify a callback if you do not want the results being stored in an array (useful for large amounts of data):
$db->query('SELECT * FROM accounts')->fetchAll(function($account) {
echo $account['name'];
});
return 'break';
Conclusion
The database class uses the MySQLi extension, this is built into PHP version >= 5.0.0. If you're using PHP version 5.0.0
to 5.3.0 you'll need install: mysqlnd.
No need to prepare statements using this class, it'll do that for you automatically (write less, do more), your queries will
be secure, just remember to make sure you escape your output using htmlspecialchars , or your preferred escaping
method.