PHP Classes

Dframe Database: Access a MySQL database using PDO

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not yet rated by the usersTotal: 218 All time: 8,291 This week: 43Up
Version License PHP version Categories
dframe-database 2.1.3Custom (specified...7Databases, PHP 7
Description 

Author

This package can access a MySQL database using PDO.

It can connect to a given MySQL database server using given configuration parameters.

The package provides several classes to build and execute SQL queries by defining condition clauses and retrieving the results.

Picture of Slawomir Kaleta
  Performance   Level  
Innovation award
Innovation award
Nominee: 3x

Winner: 1x

 

Recommendations

PDO Class
I need a class to connect to my db (mysql). Now my code is a old

Example

<?php

// include pdo helper class to use common methods
require_once '../src/Helper/PDOHelper.php';
// include pdo class wrapper
require_once '../src/class.pdowrapper.php';

// database connection setings
$dbConfig = ['host' => 'localhost', 'dbname' => 'sampledb', 'username' => 'root', 'password' => ''];
// get instance of PDO Wrapper object
$db = new PdoWrapper($dbConfig);

// get instance of PDO Helper object
$helper = new PDOHelper();

// set error log mode true to show error on screen or false to log in log file
$db->setErrorLog(true);

/**
 * run simple mysql query.
 *
 * showQuery = display executed query
 * results = get array results
 */
$q = $db->pdoQuery('select * from customers limit 5;')->showQuery()->results();
// print array result
$helper->PA($q);

/**
 * run simple mysql query with where clause
 * pass where value as an parametrised array.
 *
 * ? presenting place holder here for where clause values
 */
$q = $db->pdoQuery('select * from customers where (customernumber = ? OR customernumber = ?) ;', [103, 119])->showQuery()->results();
// print array result
$helper->PA($q);

/**
 * run simple mysql query and get third row of array results.
 *
 * result(2) = will return 3rd row of array data
 */
$q = $db->pdoQuery('select * from customers;')->showQuery()->result(2);
// print array result
$helper->PA($q);

/**
 * run mysql select query with where clause and or using parametrise array param.
 */
$q = $db->pdoQuery('select * from customers where (customernumber = ? OR contactLastName = ?) ;', [112, 'Schmitt'])->showQuery()->results();
// print array result
$helper->PA($q);

/**
 * run mysql select query with where clause and or using parametrise array param.
 */
$innerJoinSql = 'select p.checknumber, p.amount, p.paymentdate, c.customernumber, c.customerName, c.contactLastName, c.contactFirstName, c.phone, c.addressLine1, c.addressLine2, c.city, c.state, c.postalCode, c.country from payments as p inner join customers as c on p.customernumber = c.customernumber order by p.amount desc limit 2;';

$q = $db->pdoQuery($innerJoinSql)->showQuery()->results();
// print array result
$helper->PA($q);


Details

Dframe/Database

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

Dframe Documentation

Installation Composer

$ composer require dframe/database

What's included?

* MySQL PDO * MySQL Query Builder * MySQL WHERE Builder

Methods

Description | name -------- | --- MySQL query | pdoQuery() MySQL select query | select() MySQL insert query | insert() MySQL insert batch | insertBatch() MySQL update query | update() MySQL delete query | delete() MySQL truncate table | truncate() MySQL drop table | drop() MySQL describe table | describe() MySQL count records | count() Show/debug executed query | showQuery() Get last insert id | getLastInsertId() Get all last insert id | getAllLastInsertId() Get MySQL results | results() Get MySQL result | result() Get status of executed query | affectedRows() MySQL begin transactions | start() MySQL commit the transaction | end() MySQL rollback the transaction | back() Debugger PDO Error | setErrorLog()

Init Connection

<?php 
use Dframe\Database\Database;
use \PDO;

try {

    
    // Debug Config 
    $config = [
        'logDir' => APP_DIR . 'View/logs/',
        'attributes' => [
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", 
            //PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,  // Set pdo error mode silent
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // If you want to Show Class exceptions on Screen, Uncomment below code 
            PDO::ATTR_EMULATE_PREPARES => true, // Use this setting to force PDO to either always emulate prepared statements (if TRUE), or to try to use native prepared statements (if FALSE). 
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC // Set default pdo fetch mode as fetch assoc
         ]
    ];
    
    $dsn = [
        'host' => DB_HOST,
        'dbname' => DB_DATABASE,
        'dbtype' => 'mysql'
    ];
        
    $db = new Database($dsn, DB_USER, DB_PASS, $config);
    $db->setErrorLog(false); // Debug
    
}catch(\Exception $e) {
    echo 'The connect can not create: ' . $e->getMessage(); 
    exit();
}

OR

<?php 
use Dframe\Database\Database;
use \PDO;

try {

    
    // Debug Config 
    $config = [
        'log_dir' => APP_DIR . 'View/logs/',
        'attributes' => [
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", 
            //PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,  // Set pdo error mode silent
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // If you want to Show Class exceptions on Screen, Uncomment below code 
            PDO::ATTR_EMULATE_PREPARES => true, // Use this setting to force PDO to either always emulate prepared statements (if TRUE), or to try to use native prepared statements (if FALSE). 
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC // Set default pdo fetch mode as fetch assoc
         ]
    ];
    
    $db = new Database('mysql:host='.DB_HOST.';dbname=' . DB_DATABASE . ';port=3306', DB_USER, DB_PASS, $config);
    $db->setErrorLog(false); // Debug
    
}catch(\Exception $e) {
    echo 'The connect can not create: ' . $e->getMessage(); 
    exit();
}

Example - pdoQuery

Return first element array;

$result = $db->pdoQuery('SELECT * FROM table WHERE id = ?', [$id])->result();

> Note: result() will select all rows in database, so if you want select only 1 row i query connection add LIMIT 1;

Return all result array query;

$results = $db->pdoQuery('SELECT * FROM table')->results();

Update;

$affectedRows = $db->pdoQuery('UPDATE table SET col_one = ?, col_two = ?', [$col_one, $col_two])->affectedRows();

> Note: affectedRows() will return numbers modified rows;

Insert;

 
$getLastInsertId = $db->pdoQuery('INSERT INTO table (col_one, col_two) VALUES (?,?)', [$col_one, $col_two])->getLastInsertId();

> Note: getLastInsertId() will return insert ID; >

WhereChunk

Return all search result array query;

$where[] = new Dframe\Database\WhereChunk('col_id', '1'); // col_id = 1

WhereStringChunk

Return search result array query;

$where[] = new Dframe\Database\WhereStringChunk('col_id > ?', ['1']); // col_id > 1

Query builder

$query = $this->baseClass->db->prepareQuery('SELECT * FROM users');
$query->prepareWhere($where);
$query->prepareOrder('col_id', 'DESC');
$results = $this->baseClass->db->pdoQuery($query->getQuery(), $query->getParams())->results();

HavingStringChunk

$where[] = new Dframe\Database\HavingStringChunk('col_id > ?', ['1']); // col_id > 1

Original author

neerajsinghsonu/PDO_Class_Wrapper [^neerajsinghsonu/PDO_Class_Wrapper]

[^neerajsinghsonu/PDO_Class_Wrapper]: neerajsinghsonu/PDO_Class_Wrapper


  Files folder image Files (29)  
File Role Description
Files folder image.github (1 file, 1 directory)
Files folder imagedocs (2 files)
Files folder imageexample (6 files, 1 directory)
Files folder imagesrc (5 files, 2 directories)
Files folder imagetests (4 files, 1 directory)
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Read me

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:218
This week:0
All time:8,291
This week:43Up