Git Product home page Git Product logo

database's Introduction

Dframe/Database

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

Dframe Documentation

Installation Composer

$ composer require dframe/database

What's included?

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

GroupInsertBatchHelper

/**
 * Multiple insert products with details in to tables
 */
$InsertBatchHelper = new InsertBatchHelper();

/**
* -----------------------------------------------------------------
* Prepare Product
* -----------------------------------------------------------------
*/
foreach ($data as $item) {
    
    $somePrimaryKey = md5($item->name.$item->price.$item->clientId);
    /** 
     *  First Query
     */    
    $Field = $InsertBatchHelper
        ->addRequireFields(
            [
                'id' => $somePrimaryKey,
                'name' => $item->name,
            ]
        )
        ->addField('client_id', $item->clientId, true)
        ->isCondition('available', 1, false);
    
    /**
     * Generate query string without params
     */
    $InsertBatchHelper->prepareInsert('products', $Field->getValues(), $Field->getColsForUpdate());

   /** 
    *  Second Query
    */
    $Field = $InsertBatchHelper
        ->addRequireFields(
            [
                'id' => $somePrimaryKey,
                'size' => $item->size,
                'price' => $item->price,
            ]
        )
        ->addField('client_id', $item->clientId, true)
        ->isCondition('available', 1, false);
    
    /**
     * Generate query string without params
     */
    $InsertBatchHelper->prepareInsert('products_details', $Field->getValues(), $Field->getColsForUpdate());
    
}

/** 
 * Get first and second query  
 */
$getQueriesBatchInsert = $InsertBatchHelper->getQueriesBatchInsert();

/**
 * Generate query for first and second query with params and run query
 */
foreach ($getQueriesBatchInsert as $sql => $queryBatchInsert) {

    $sqlProduct = $queryBatchInsert['sql'];
    $valuesProduct = $queryBatchInsert['data'];
    $updateColsProduct = $queryBatchInsert['updateCols'];
    
    $query = $this->baseClass->prepareBatchInsert($sqlProduct, $valuesProduct, $updateColsProduct);
    $results = $this->baseClass->db->pdoQuery($query->getQuery(), $query->getParams())->results();
 
}

Original author

neerajsinghsonu/PDO_Class_Wrapper 1

Footnotes

  1. neerajsinghsonu/PDO_Class_Wrapper โ†ฉ

database's People

Contributors

dusta avatar peter279k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

peter279k

database's Issues

Wrong order parametr LIMIT

Describe the bug
Parameters are the opposite

 public function prepareLimit($limit, $offset = null)
    {
        if ($offset) {
            $this->setLimit = ' LIMIT ' . $limit . ', ' . $offset . '';
        } else {
            $this->setLimit = ' LIMIT ' . $limit . '';
        }

        return $this;
    }

Should be

    public function prepareLimit($limit, $offset = null)
    {
        if ($offset) {
            $this->setLimit = ' LIMIT ' . $offset . ', ' . $limit . '';
        } else {
            $this->setLimit = ' LIMIT ' . $limit . '';
        }

        return $this;
    }

Update __construct

Before

public function __construct($dsn, $username, $password, $config = ['logDir' => '', 'attributes' => []])

After

<?php
public function __construct($dsn, $username, $password, $config = ['logDir' => '', 'options' => []])

Incorrect order Having

Before

    /**
     * GetQuery function.
     *
     * @return string
     */
    public function getQuery()
    {
        $sql = $this->setQuery;
        $sql .= $this->getWhere();
        $sql .= $this->getGroupBy();
        $sql .= $this->getOrderBy();
        $sql .= $this->getHaving();
        $sql .= $this->getLimit();

        $this->setQuery = null;
        $this->setWhere = null;
        $this->setHaving = null;
        $this->setOrderBy = null;
        $this->setGroupBy = null;
        $this->setLimit = null;

After

    /**
     * GetQuery function.
     *
     * @return string
     */
    public function getQuery()
    {
        $sql = $this->setQuery;
        $sql .= $this->getWhere();
        $sql .= $this->getGroupBy();
        $sql .= $this->getHaving();
        $sql .= $this->getOrderBy();
        $sql .= $this->getLimit();

        $this->setQuery = null;
        $this->setWhere = null;
        $this->setGroupBy = null;
        $this->setHaving = null;
        $this->setOrderBy = null;
        $this->setLimit = null;

Native dsn

Before

    $dbConfig = [
        'host' => DB_HOST,
        'dbname' => DB_DATABASE,
        'username' => DB_USER,
        'password' => DB_PASS
    ];
    
    // 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
         ]
    ];
    $db = new Database($dbConfig, $config);

After Example 1

    // 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);

After Example 2

  // 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);
   

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.