A PHP MySQL database client class to simplify database access

Overview

Secure Database PHP Class

A PHP MySQL database client class to simplify database access.

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.

Let's Start!

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 PHP function, or your preferred escaping method.

PS: The transactions query aren't yet supported on this class.

How To Use

Download the source file

Download the file db.php. It contains the client PHP class named db.

Connect to MySQL database:

include 'db.php';

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'example';

$db = new db($dbhost, $dbuser, $dbpass, $dbname); // or update the default values of the parameters in db.php

Fetch a record from a database:

$account = $db->query('SELECT * FROM accounts WHERE username = ? AND password = ?', 'test', 'test')->fetchArray();
echo $account['name'];

Or you could do:

$account = $db->query('SELECT * FROM accounts WHERE username = ? AND password = ?', array('test', 'test'))->fetchArray();
echo $account['name'];

Fetch multiple records from a database:

$accounts = $db->query('SELECT * FROM accounts')->fetchAll();

foreach ($accounts as $account) {
	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'];
});

If you need to break the loop you can add:

return 'break';

Update a record:

$Update_Password = $db->query('UPDATE accounts SET password = ? WHERE username = ?', 'newpass', 'test');

And you can check if the action was success or fail by doing the following:

if($Update_Password) {
    // Success
} else {
    // Failure
}

Get the number of rows:

$accounts = $db->query('SELECT * FROM accounts');
echo $accounts->numRows();

Get the affected number of rows:

$insert = $db->query('INSERT INTO accounts (username,password,email,name) VALUES (?,?,?,?)', 'test', 'test', '[email protected]', 'Test');
echo $insert->affectedRows();

Get the total number of queries:

echo $db->query_count;

Get the last insert ID:

echo $db->lastInsertID();

Close the database:

$db->close();

Disclaimer

The original class was published by David Adams on 2020-03-05 at https://codeshack.io/super-fast-php-mysql-database-class/ under the MIT license.

I brought it here to Github in order to improve it with the help of anybody that is interested in this piece of code. If you find bugs or want to improve the code, please create an issue or pull request. Thanks.

You might also like...
PHP demo application showing how to access the Hubstaff Public API

Public API PHP Demo This repository contains a simple sample cli tool that shows off how to access the Hubstaff public api via PHP. The core access is

Formcreator is a plugin which allow creation of custom forms of easy access
Formcreator is a plugin which allow creation of custom forms of easy access

Formcreator is a plugin which allow creation of custom forms of easy access. At the same time, the plugin allow the creation of one or more tickets when the form is filled.

Moodle plugin to limit the access to course content according to the user level in Block Game.

Moodle plugin to limit the access to course content according to the user level in Block Game.

A simple API with Guzzle wrapper, providing easy access to wppconnect's endpoints.

WPPConnect Team Wppconnect Laravel Client A simple API with Guzzle wrapper, providing easy access to wppconnect's endpoints. Requirements PHP 7.4 or n

 Rafel is Remote Access Tool Used to Control Victims Using WebPanel With More Advance Features..
Rafel is Remote Access Tool Used to Control Victims Using WebPanel With More Advance Features..

Rafel is Remote Access Tool Used to Control Victims Using WebPanel With More Advance Features..

This package makes it easy to add early access mode to your existing application.
This package makes it easy to add early access mode to your existing application.

This package makes it easy to add early access mode to your existing application. This is useful for when you want to launch a product and need to gat

A tool for managing SSH key access to any number of servers.

Revons - SSH Key Authority Features Easily manage SSH key access for all accounts on your servers. Manage user access and server-to-server access rule

Free ZIP Code API - Free Access to Worldwide Postal Code Data

About Zipcodebase - Free Zip Code API Zipcodebase is a zip code API that was founded in 2019 to solve common issues with postal code data. As we have

Tango is a command-line tool for analyzing access logs šŸ’ƒ
Tango is a command-line tool for analyzing access logs šŸ’ƒ

Tango Tool to get insights from the server access logs Tango is a dependency-free command-line tool for analyzing access logs šŸ’ƒ Currently, work on th

Owner
Khader Handal
Iā€™m an ICT specialist based in Bethlehem, with over 10 years of professional experience in the industry.
Khader Handal
A plugin simplify 1v1 mode for Pocketmine-MP!

A plugin simplify 1v1 mode for Pocketmine-MP!

HoangNotGay 5 Apr 17, 2022
Exploiting and fixing security vulnerabilities of an old version of E-Class. Project implemented as part of the class YS13 Cyber-Security.

Open eClass 2.3 Development of XSS, CSRF, SQLi, RFI attacks/defences of an older,vulnerable version of eclass. Project implemented as part of the clas

Aristi_Papastavrou 11 Apr 23, 2022
This example shows how to use Anychart library with the PHP programming language, Laravel framework and MySQL database.

PHP basic template This example shows how to use Anychart library with the PHP programming language, Laravel framework and MySQL database. Running To

AnyChart Integrations and Templates 23 Jul 17, 2022
A forum software written in vanilla PHP with a MariaDB/MySQL database.

GloomyBB GloomyBB is a simple forum software written in vanilla PHP with a MariaDB/MySQL database. It is currently still in early development but is u

John Vinh 3 Nov 2, 2022
Free Functions To Connect To The Database ( Mysql ) For Php Programmers

Update ?? The biggest update ever DB-php Free Functions To Connect To The Database ( Mysql ) For Php Programmers This Version : 2.0 connect to databas

Ali 3 May 27, 2022
A project of a Login screen made in PHP/CSS3/HTML5/JS with MySQL database integration

A project of a Login screen made in PHP/CSS3/HTML5/JS with MySQL database integration. And animations made with CSS3 and JavaScript itself! ??

Marcel Leite de Farias 2 Apr 26, 2022
A web application built on PHP for user to view their credit information in their mysql database

TheCreditInfo Table of Content About Inspiration Technologies Client Pages Usage About Credere is a website created to help you track your credit hist

Abdul-Baseet Shabi 0 Jul 21, 2022
QueryHandler - Handling PDO ' s query with mySQL database

QueryHandler this class's method are static .... that mean you don't need to create an object to use it . All methodes will return an Exception if it

null 7 Aug 9, 2022
TiDB is an open source distributed HTAP database compatible with the MySQL protocol

What is TiDB? TiDB ("Ti" stands for Titanium) is an open-source NewSQL database that supports Hybrid Transactional and Analytical Processing (HTAP) wo

PingCAP 33.1k Jan 9, 2023
PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects.

?? Yell PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects. Requirement

Zeeshan Ahmad 20 Dec 8, 2018