• Stars
    star
    111
  • Rank 314,510 (Top 7 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 9 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PDO wrapper for MySQL

PDO Wrapper

This PDO wrapper, is a collection of methods for working with a database this includes selecting, inserting, updating and deleting records.

V2+ has been rewritten for the old docs please see V1 branch

Latest Version on Packagist Total Downloads

Logo

This PDO wrapper, is a collection of methods for working with a database this includes selecting, inserting, updating and deleting records.

V2+ has been rewritten for the old docs please see V1 branch

Upgrade from V1

Version 2 is now namespaced as Dcblogdev instead of Daveismyname

Also the methods get() and select() have been removed.

Instead of ::get() a new instance of the class used new Database($args)

Select has been replaced with ->rows() and ->row() or ->run()

Quick Reference

//create table
$db->raw("CREATE TABLE demo (id int auto_increment primary key, name varchar(255))");

//use PDO directly
$db->getPdo()->query('Select username FROM users')->fetchAll();

//use run to query and chain methods
$db->run("SELECT * FROM users")->fetchAll();
$db->run("SELECT * FROM users")->fetch();
$db->run("SELECT * FROM users WHERE id = ?", [$id])->fetch();
//select using array instead of object
$db->run("SELECT * FROM users")->fetch(PDO::FETCH_ASSOC);

//get by id
$db->getById('users', 2);

//get all rows
$db->rows("SELECT title FROM posts");
//get all rows with placeholders
$db->rows("SELECT title FROM posts WHERE user_id = ?", [$user_id]);

//get single row
$db->row("SELECT title FROM posts");
//get single row with placeholders
$db->row("SELECT title FROM posts WHERE user_id = ?", [$user_id]);

//count
$db->count("SELECT id FROM posts");
$db->count("SELECT id FROM posts WHERE category_id = ?", [$category_id]);

//insert
$id = $db->insert('users', ['username' => 'Dave', 'role' => 'Admin']);

//last inserted id
$db->lastInsertId()();

//update
$db->update('users', ['role' => 'Editor'], ['id' => 3]);

//delete from table with a where claus and a limit of 1 record
$db->delete('posts', ['type_id' => 'draft'], $limit = 1);

//delete from table with a where claus and a limit of 10 record
$db->delete('posts', ['type_id' => 'draft'], $limit = 10);

//delete all from table with a where claus and a limit of 10 record
$db->delete('posts', ['type_id' => 'draft'], null);

//delete all from table
$db->deleteAll('posts');

//delete by id from table
$db->deleteById('posts', 2);

//delete by ids from table
$db->deleteById('posts', '2,4,7');

//truncate table
$eb->truncate('posts');

Install

Using composer include the repository by typing the following into a terminal

composer require dcblogdev/pdo-wrapper

Set the DB credentials. Finally, create an instance of the classes.

use Dcblogdev\PdoWrapper\Database;

// make a connection to mysql here
$options = [
    //required
    'username' => '',
    'database' => '',
    //optional
    'password' => '',
    'type' => 'mysql',
    'charset' => 'utf8',
    'host' => 'dev',
    'port' => '3309'
];

$db = new Database($options);

Accessing PDO You can call getPdo()` to get access to PDO directly:

$db->getPdo()

This allows to chain calls:

$db->getPdo()->query($sql)->fetch();

Querying

All queries use prepared statements, calling ->run() returns a PDO option that can be chained:

Select multiple records:

$db->run("select * FROM users")->fetchAll();

Select a single record:

$db->run("select * FROM users")->fetch();

Select multiple records using ->rows

$db->rows("select * FROM table");

Select single record using ->row

$db->row("select * FROM table");

To select records based on user data instead of passing the data to the query directly use a prepared statement, this is safer and stops any attempt at sql injections.

Names placeholders

$db->row("select username FROM users WHERE id = :id and email = :email", ['id' => 1, ':email' => '[email protected]']);

Annonomus placeholders

$db->row("select username FROM users WHERE id = ? and email = ?", [1, '[email protected]']);

The above query will return the username from a users table where the id and email match. The id and email is passed seperartly in an array.

Instead of passing in an id and email to the query directly a placeholder is used :id and :email (or ? can be used) then an array is passed the keys in the array matches the placeholder and is bound, so the database will get both the query and the bound data.

Data returned from the query will be returns as an object this can be changed by passing a third param containing PDO::FETCH_ASSOC.

To use the object loop through it, a typical example:

$rows = $db->rows("firstName, lastName FROM username ORDER BY firstName, lastName");
foreach ($rows as $row) {
    echo "<p>$row->firstName $row->lastName</p>";
}

Select Single Record

Using row() will return only a single result. Like rows it accepts params being passed in an array as a second argument.

Names placeholders

$db->row("column FROM table where id=:id", ['id' => 23]);

Anonymous placeholders

$db->row("column FROM table where id=?", [23]);

Another way to select a single record using the table and id by calling ->getById

$db->getById('users', $id);

Raw

A raw query is a query that does not run through a prepared statement and will execute the query passed directly. Useful when creating a table.

$db->raw("CREATE TABLE IF NOT EXISTS users (
  id INT(11) NOT NULL AUTO_INCREMENT,
  firstName VARCHAR(255) NOT NULL,
  lastnName VARCHAR(255) NOT NULL,
  email VARCHAR(255) NOT NULL,
  PRIMARY KEY (id))"
);

Count

To count records call the count method. This method expects the table name and column name (optional).

$db->count('users');

If the table has no column id

$db->count('users', 'user_id');

Insert

Data is inserted by calling the insert method it expects the table name followed by an array of key and values to insert in to the database.

$data = [
    'firstName' => 'Joe',
    'lastnName' => 'Smith',
    'email' => '[email protected]'
];
$db->insert('users', $data);

The insert automatically returns the last inserted id by returning 'lastInsertId' to collect the id:

$id = $db->insert('users', $data);

Updating

To update an existing record the update method is called. This method expects the table, array of data to update, and a second array containing the where condition.

$data = [
    'firstName' => 'Joe',
    'lastnName' => 'Smith',
    'email' => '[email protected]'
];
$where = ['id' => 2];
$db->update('users', $data, $where);

Or:

$update = [ 
	'data' => [
	    'firstName' => 'Joe',
	    'lastnName' => 'Smith',
	    'email' => '[email protected]'
	],
	'where' => [
        'id' => 2
    ]
];

$db->update('users', $update['data'], $update['where']);

Delete

To delete records call the delete method. This method expects the table name and an array of the where condition.

$where = ['id' => 2];
$db->delete('users', $where);

This will delete a single record to set the limit pass a third parameter containing the number to limit to or to remove the limit pass null as a third param.

$db->delete('users', $where, 10);  //delete 10 records matcing the where
$db->delete('users', $where, null); //delete all records matching the where

Delete All

To delete all records for a given table

$db->deleteAll('users');

Delete by Id

To delete a record by its table and id

$db->deleteById('users', $id);

Delete Multiple In

To delete multiple records where ids are in a specific column, this uses WHERE id IN (4,5,6)

$db->deleteByIds('users', 'id', '4,5,6');

Truncate

To empty a table of all contents call the truncate method. Passing only the table name.

$db->truncate('users');

More Repositories

1

loginregister

Login and Registration system
PHP
313
star
2

laravel-db-sync

Sync a remote DB to a local DB
PHP
308
star
3

laravel-admintw

Laravel Starter Kit | TALL admin theme
PHP
249
star
4

laravel-sent-emails

Store outgoing emails in Laravel
PHP
248
star
5

laravel-microsoft-graph

Laravel package for Microsoft Graph API (Microsoft365)
PHP
120
star
6

simple-blog-part-1-build

Create a blog from scratch with PHP
PHP
94
star
7

pagination

Paginate record sets, not tied in directly to a database.
PHP
75
star
8

admintw

Admin theme built with Tailwindcss and AlpineJS
CSS
68
star
9

laravel-module-generator

Generate boilerplate code for Laravel
PHP
68
star
10

laravel-xero

Laravel package for working with Xero API
PHP
37
star
11

laravel-blade-components

Laravel Blade components collection
Blade
36
star
12

autocomplete

Autocomplete with jQuery and PHP
PHP
26
star
13

laravel-dropbox

A Laravel package for working with Dropbox API v2.
PHP
24
star
14

simple-cms

Building a content management system from scratch
PHP
23
star
15

simple-blog-part-6-pagination

Create a blog from scratch with PHP
PHP
20
star
16

gallery-from-folder

Creating an image gallery from a folder of images automatically
PHP
19
star
17

form-to-pdf

PHP
16
star
18

laravel-companies-house

Laravel package for Companies House
PHP
10
star
19

simple-blog-part-2-seo-urls

Create a blog from scratch with PHP
PHP
10
star
20

exportcsv

Export arrays to CSV
PHP
9
star
21

simple-blog-part-4-categories

Create a blog from scratch with PHP
PHP
9
star
22

laravel-filters

Save and reuse query based filters
PHP
9
star
23

sql-import

PDO import sql from a .sql file
PHP
9
star
24

duplicate-form-sections

JavaScript
8
star
25

laravel-box

Laravel package for BOX API
PHP
8
star
26

language-changer-with-PHP

How to create a language changer with PHP
PHP
7
star
27

dropboxbackup

Backup to Dropbox with PHP
PHP
7
star
28

imap

IMAP class for reading imap emails with PHP
PHP
6
star
29

laravel-eventbrite

Laravel package for working with Eventbrite's API
PHP
6
star
30

autoscroll

Autoscroll with jQuery
HTML
6
star
31

php-find-and-replace-json

PHP
6
star
32

laravel-countries

A Laravel countries list package
PHP
6
star
33

fullcalendar

JavaScript
6
star
34

phpcart

Simple framework agnostic shopping cart (Built by anam-hossain/phpcart)
PHP
6
star
35

simple-blog-part-5-sidebar-categories-and-archives

Create a blog from scratch with PHP
PHP
5
star
36

laravel-nestable

Laravel 5 nested category/menu generator
PHP
5
star
37

MacawDemo

Foundations for a router application
PHP
5
star
38

mini

Mini is a small Laravel application with 2 modules to go with the book Laravel: The Modular Way
PHP
5
star
39

importing-csv-sample-data

Importing CSV (spreadsheet) data into a MySQL Database using PHP
5
star
40

Load-MP3-s-from-a-folder

Load MP3's from a folder with option to play on page
PHP
4
star
41

addhourtodatetimepicker

adds an hour to the To field from the datetimepicker
JavaScript
3
star
42

filament-courses-demo

Example related resources
PHP
3
star
43

laravel-tags

PHP
3
star
44

laravel-api-starter

PHP
3
star
45

laravel-hashnode

a wrapper around Hashnode's API for Laravel
PHP
3
star
46

cpanelemails

PHP
2
star
47

dcblogcomments

2
star
48

dynamically-binding-select-menus-with-php-jquery

files to accompany tutorial
PHP
2
star
49

reservedwords

An array of reserved words for PHP
PHP
2
star
50

dotfiles

Shell
2
star
51

countries-list

PHP
1
star
52

captcha

files to accompany tutorial
PHP
1
star
53

docs.laravelmodules.com

1
star
54

dcblogdev

1
star
55

crud-example

PHP
1
star
56

sms-platform

a WIP experimental project for trying out InertiaJS
PHP
1
star
57

phpstorm-keybindings

1
star
58

hashblog

PHP
1
star
59

WP-Forrst-Posts

WP Forrst Posts allows you to display your 25 latest Forrst (public) posts using the Forrst API. The posts from Forrst are cached to avoid any API limits. The cached posts are stored in a file called forrstdata.php this file is only used to read data that has been cached.
PHP
1
star