PHP MySQLi Class Documentation

Similar documents

Chapters 10 & 11 PHP AND MYSQL

Ark Database Documentation

Networks and Web for Health Informatics (HINF 6220) Tutorial 13 : PHP 29 Oct 2015

CHAPTER 10. Connecting to Databases within PHP

Exam Questions 1z0-882

Sheeri Cabral. Are You Getting the Best Out of Your MySQL Indexes? Slides

"Charting the Course... Intermediate PHP & MySQL Course Summary

Paris Documentation. Release. Jamie Matthews and Simon Holywell

Although this code is under construction the interfaces are unlikely to change, if only because we use it in production.

WooCommerce REST API Integration. October 27, 2018

Lecture 13: MySQL and PHP. Monday, March 26, 2018

SQL Injection SPRING 2018: GANG WANG

INTERMEDIATE SQL GOING BEYOND THE SELECT. Created by Brian Duffey

Retrieving Query Results

PHP Development - Introduction

Importing to WIRED Contact From a Database File. Reference Guide

Mysql Insert Manual Timestamp Into Datetime Field

Chapter 7 PHP Files & MySQL Databases

Torndb Release 0.3 Aug 30, 2017

Database Connectivity using PHP Some Points to Remember:

Oracle Syllabus Course code-r10605 SQL

PHP: Cookies, Sessions, Databases. CS174. Chris Pollett. Sep 24, 2008.

Automated SQL Ownage Techniques. OWASP October 30 th, The OWASP Foundation

API Gateway Version September Key Property Store User Guide

Web Security. Attacks on Servers 11/6/2017 1

Table of Contents. Developer Manual...1

Oracle 1Z MySQL 5.6 Developer.

CorreLog. SQL Table Monitor Adapter Users Manual

Chapter 3. Introduction to relational databases and MySQL. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C3

MySQL Protocol Tutorial

Databases (MariaDB/MySQL) CS401, Fall 2015

MySQL: Access Via PHP

IELM 511 Information Systems Design Labs 5 and 6. DB creation and Population

CS 2316 Homework 9a Login Due: Friday, November 2nd, before 11:55 PM Out of 100 points. Premise

DATABASE SYSTEMS. Database programming in a web environment. Database System Course, 2016

In This Lecture. Yet More SQL SELECT ORDER BY. SQL SELECT Overview. ORDER BY Example. ORDER BY Example. Yet more SQL

MySQL for Developers. Duration: 5 Days

1 28/06/ :17. Authenticating Users General Information Manipulating Data. REST Requests

Sql Server Syllabus. Overview

Introduction to relational databases and MySQL

A SQL Injection : Internal Investigation of Injection, Detection and Prevention of SQL Injection Attacks

MySQL for Developers. Duration: 5 Days

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Joomla

COMP284 Scripting Languages Lecture 13: PHP (Part 5) Handouts

OpenEMR ZF2 Module Installer. 1. Authentication to Database and SQL Query Handling. 1.1 Zend\Db\Adapter. Introduction

To insert a record into a table, you must specify values for all fields that do not have default values and cannot be NULL.

Transaction Safe Feature in MySQL Databases

Chapter 9: Working With Data

Build a Professional Website Using Joomla 1.5

PHP and MySgi. John Wiley & Sons, Inc. 24-HOUR TRAINER. Andrea Tarr WILEY

HPCC JDBC Driver. Boca Raton Documentation Team

Richard Crowley

MySQL 8.0 What s New in the Optimizer

SQL stands for Structured Query Language. SQL lets you access and manipulate databases

DB2 SQL Class Outline

What is SQL? Toolkit for this guide. Learning SQL Using phpmyadmin

MySQL Schema Best Practices

Lecture 7: Web hacking 3, SQL injection, Xpath injection, Server side template injection, File inclusion

PHP for PL/SQL Developers. Lewis Cunningham JP Morgan Chase

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

Model Question Paper. Credits: 4 Marks: 140

Lecture 5. Monday, September 15, 2014

DATABASE SYSTEMS. Database programming in a web environment. Database System Course,

CS 2316 Homework 9a GT Pizza Login Due: Wednesday November 6th Out of 100 points. Premise

Effective Software Development with MySQL

SQL functions fit into two broad categories: Data definition language Data manipulation language

Chapter 8: Working With Databases & Tables

newauth Documentation

AN INTRODUCTION TO WEB PROGRAMMING. Dr. Hossein Hakimzadeh Department of Computer and Information Sciences Indiana University South Bend, IN

MySQL 101. Designing effective schema for InnoDB. Yves Trudeau April 2015

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

Configuration Setting

GridDB Advanced Edition SQL reference

School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University

Mysql Manual Order By Multiple Columns Example

GLPi Developer Documentation Documentation

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

PHPRad. PHPRad At a Glance. This tutorial will show you basic functionalities in PHPRad and

1z0-882.exam.55q 1z0-882 Oracle Certified Professional, MySQL 5.6 Developer


Table of Contents. Single Sign On 1

Memory may be insufficient. Memory may be insufficient.

Module - P7 Lecture - 15 Practical: Interacting with a DBMS

zf-doctrine-audit Documentation Release latest


Previously everyone in the class used the mysql account: Username: csci340user Password: csci340pass

Enterprise Reporting -- APEX

ITS331 IT Laboratory I: (Laboratory #11) Session Handling

General Coding Standards

CSC 405 Computer Security. Web Security

T-SQL Training: T-SQL for SQL Server for Developers

GridDB Advanced Edition SQL reference

PERL DATABASE ACCESS

DPD API Reference Documentation

Professional PHP for working with MySQL

Locate your Advanced Tools and Applications

5. Single-row function

SQL Data Query Language

Transcription:

PHP MySQLi Class Documentation Release 1.0 Read the Docs Sep 16, 2017

Contents 1 Installation 3 2 Initialization 5 2.1 Advanced initialization:......................................... 5 3 Insert Query 7 3.1 Simple Example............................................. 7 3.2 Insert with on duplicate key update................................... 7 3.3 Replace Query.............................................. 8 4 Update Query 9 5 Select Query 11 6 Pagination 13 6.1 Result transformation / map....................................... 13 6.2 Defining a return type.......................................... 13 7 Delete Query 15 8 Running raw SQL queries 17 8.1 More advanced examples:........................................ 17 9 Query Keywords 19 10 Ordering method 21 11 Grouping method 23 12 Properties sharing 25 13 JOIN method 27 14 Subqueries 29 15 EXISTS / NOT EXISTS condition 31 16 Has method 33 i

17 Helper methods 35 18 Transaction helpers 37 19 Query exectution time benchmarking 39 20 Indices and tables 41 ii

PHP MySQLi Class Documentation, Release 1.0 Note: This is not an official documentation. Official API documentation is available in the GitHub repo here. Contents 1

PHP MySQLi Class Documentation, Release 1.0 2 Contents

CHAPTER 1 Installation To utilize this class, first import MysqliDb.php into your project, and require it. require_once ( MysqliDb.php ); Installation with composer It is also possible to install library via composer composer require joshcam/mysqli-database-class:dev-master 3

PHP MySQLi Class Documentation, Release 1.0 4 Chapter 1. Installation

CHAPTER 2 Initialization Simple initialization with utf8 charset set by default: $db = new MysqliDb ( host, username, password, databasename ); Advanced initialization: $db = new MysqliDb (Array ( host => host, username => username, password => password, db => databasename, port => 3306, prefix => my_, charset => utf8 )); table prefix, port and database charset params are optional. If no charset should be set charset, set it to null Also it is possible to reuse already connected mysqli object: $mysqli = new mysqli ( host, username, password, databasename ); $db = new MysqliDb ($mysqli); If no table prefix were set during object creation its possible to set it later with a separate call: $db->setprefix ( my_ ); If you need to get already created mysqlidb object from another class or function use function init () { // db staying private here $db = new MysqliDb ( host, username, password, databasename ); 5

PHP MySQLi Class Documentation, Release 1.0 function myfunc () { // obtain db object created in init () $db = MysqliDb::getInstance();... } 6 Chapter 2. Initialization

CHAPTER 3 Insert Query Simple Example $data = Array ( login => admin, firstname => John, lastname => Doe ); $id = $db->insert ( users, $data); if($id) echo user was created. Id=. $id; Insert with functions use $data = Array ( login => admin, active => true, firstname => John, lastname => Doe, password => $db->func( SHA1(?),Array ( secretpassword+salt )), // password = SHA1( secretpassword+salt ) createdat => $db->now(), // createdat = NOW() expires => $db- >now( +1Y ) // expires = NOW() + interval 1 year // Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [ Y]ear ); $id = $db->insert ( users, $data); if ($id) echo user was created. Id=. $id; else echo insert failed:. $db->getlasterror(); Insert with on duplicate key update $data = Array ( login => admin, firstname => John, lastname => Doe, createdat => $db->now(), updatedat => $db->now(), ); $updatecolumns = Array ( updatedat ); $lastinsertid = id ; $db->onduplicate($updatecolumns, $lastinsertid); $id = $db->insert ( users, $data); 7

PHP MySQLi Class Documentation, Release 1.0 Replace Query Replace() method implements same API as insert(); 8 Chapter 3. Insert Query

CHAPTER 4 Update Query $data = Array ( firstname => Bobby, lastname => Tables, editcount => $db->inc(2), // edit- Count = editcount + 2; active => $db->not() // active =!active; ); $db->where ( id, 1); if ($db->update ( users, $data)) echo $db->count. records were updated ; else echo update failed:. $db->getlasterror(); update() also support limit parameter: $db->update ( users, $data, 10); // Gives: UPDATE users SET... LIMIT 10 9

PHP MySQLi Class Documentation, Release 1.0 10 Chapter 4. Update Query

CHAPTER 5 Select Query After any select/get function calls amount or returned rows is stored in $count variable $users = $db->get( users ); //contains an Array of all users $users = $db->get( users, 10); //contains an Array 10 users or select with custom columns set. Functions also could be used $cols = Array ( id, name, email ); $users = $db->get ( users, null, $cols); if ($db->count > 0) foreach ($users as $user) { print_r ($user); } or select just one row $db->where ( id, 1); $user = $db->getone ( users ); echo $user[ id ]; $stats = $db->getone ( users, sum(id), count(*) as cnt ); echo total.$stats[ cnt ]. users found ; or select one column value or function result $count = $db->getvalue ( users, count(*) ); echo {$count} users found ; select one column value or function result from multiple rows: $logins = $db->getvalue ( users, login, null); // select login from users $logins = $db->getvalue ( users, login, 5); // select login from users limit 5 foreach ($logins as $login) echo $login; 11

PHP MySQLi Class Documentation, Release 1.0 12 Chapter 5. Select Query

CHAPTER 6 Pagination Use paginate() instead of get() to fetch paginated result $page = 1; // set page limit to 2 results per page. 20 by default $db->pagelimit = 2; $products = $db- >arraybuilder()->paginate( products, $page); echo showing $page out of. $db->totalpages; Result transformation / map Instead of getting an pure array of results its possible to get result in an associative array with a needed key. If only 2 fields to fetch will be set in get(), method will return result in array($k => $v) and array ($k => array ($v, $v)) in rest of the cases. $user = $db->map ( login )->ObjectBuilder()->getOne ( users, login, id ); Array ( ) [user1] => 1 $user = $db->map ( login )->ObjectBuilder()->getOne ( users, id,login,createdat ); Array ( ) [user1] => stdclass Object ( [id] => 1 [login] => user1 [createdat] => 2015-10-22 22:27:53 ) Defining a return type MysqliDb can return result in 3 different formats: Array of Array, Array of Objects and a Json string. To select a return type use ArrayBuilder(), ObjectBuilder() and JsonBuilder() methods. Note that ArrayBuilder() is a default return type 13

PHP MySQLi Class Documentation, Release 1.0 // Array return type $= $db->getone( users ); echo $u[ login ]; // Object return type $u = $db- >ObjectBuilder()->getOne( users ); echo $u->login; // Json return type $json = $db->jsonbuilder()- >getone( users ); 14 Chapter 6. Pagination

CHAPTER 7 Delete Query $db->where( id, 1); if($db->delete( users )) echo successfully deleted ; 15

PHP MySQLi Class Documentation, Release 1.0 16 Chapter 7. Delete Query

CHAPTER 8 Running raw SQL queries $users = $db->rawquery( SELECT * from users where id >=?, Array (10)); foreach ($users as $user) { } print_r ($user); To avoid long if checks there are couple helper functions to work with raw query select results: Get 1 row of results: $user = $db->rawqueryone ( select * from users where id=?, Array(10)); echo $user[ login ]; // Object return type $user = $db->objectbuilder()->rawqueryone ( select * from users where id=?, Array(10)); echo $user->login; Get 1 column value as a string: $password = $db->rawqueryvalue ( select password from users where id=? limit 1, Array(10)); echo Password is {$password} ; NOTE: for a rawqueryvalue() to return string instead of an array limit 1 should be added to the end of the query. Get 1 column value from multiple rows: $logins = $db->rawqueryvalue ( select login from users limit 10 ); foreach ($logins as $login) echo $login; More advanced examples: $params = Array(1, admin ); $users = $db->rawquery( SELECT id, firstname, lastname FROM users WHERE id =? AND login =?, $params); print_r($users); // contains Array of returned rows // will handle any SQL query $params = Array(10, 1, 10, 11, 2, 10); $q = ( SELECT a FROM t1 WHERE a =? AND B =? ORDER BY a LIMIT? ) UNION ( 17

PHP MySQLi Class Documentation, Release 1.0 SELECT a FROM t2 WHERE a =? AND B =? ORDER BY a LIMIT? ) ; $resutls = $db->rawquery ($q, $params); print_r ($results); // contains Array of returned rows 18 Chapter 8. Running raw SQL queries

CHAPTER 9 Query Keywords To add LOW PRIORITY DELAYED HIGH PRIORITY IGNORE and the rest of the mysql keywords to INSERT (), REPLACE (), GET (), UPDATE (), DELETE() method or FOR UPDATE LOCK IN SHARE MODE into SELECT (): $db->setqueryoption ( LOW_PRIORITY )->insert ($table, $param); // GIVES: INSERT LOW_PRIORITY INTO table... $db->setqueryoption ( FOR UPDATE )->get ( users ); // GIVES: SELECT * FROM USERS FOR UP- DATE; Also you can use an array of keywords: $db->setqueryoption (Array( LOW_PRIORITY, IGNORE ))->insert ($table,$param); // GIVES: IN- SERT LOW_PRIORITY IGNORE INTO table... Same way keywords could be used in SELECT queries as well: $db->setqueryoption ( SQL_NO_CACHE ); $db->get( users ); // GIVES: SELECT SQL_NO_CACHE * FROM USERS; Optionally you can use method chaining to call where multiple times without referencing your object over an over: $results = $db ->where( id, 1) ->where( login, admin ) ->get( users ); 19

PHP MySQLi Class Documentation, Release 1.0 20 Chapter 9. Query Keywords

CHAPTER 10 Ordering method $db->orderby( id, asc ); $db->orderby( login, Desc ); $db->orderby( RAND () ); $results = $db- >get( users ); // Gives: SELECT * FROM users ORDER BY id ASC,login DESC, RAND (); Order by values example: $db->orderby( usergroup, ASC, array( superuser, admin, users )); $db->get( users ); // Gives: SE- LECT * FROM users ORDER BY FIELD (usergroup, superuser, admin, users ) ASC; If you are using setprefix () functionality and need to use table names in orderby() method make sure that table names are escaped with. $db->setprefix ( t_ ); $db->orderby ( users.id, asc ); $results = $db->get ( users ); // WRONG: That will give: SELECT * FROM t_users ORDER BY users.id ASC; $db->setprefix ( t_ ); $db->orderby ( users.id, asc ); $results = $db->get ( users ); // CORRECT: That will give: SELECT * FROM t_users ORDER BY t_users.id ASC; 21

PHP MySQLi Class Documentation, Release 1.0 22 Chapter 10. Ordering method

CHAPTER 11 Grouping method $db->groupby ( name ); $results = $db->get ( users ); // Gives: SELECT * FROM users GROUP BY name; Join table products with table users with LEFT JOIN by tenantid 23

PHP MySQLi Class Documentation, Release 1.0 24 Chapter 11. Grouping method

CHAPTER 12 Properties sharing Its is also possible to copy properties $db->where ( agentid, 10); $db->where ( active, true); $customers = $db->copy (); $res = $customers->get ( customers, Array (10, 10)); // SELECT * FROM customers where agentid = 10 and active = 1 limit 10, 10 $cnt = $db->getvalue ( customers, count(id) ); echo total records found:. count(id) FROM users where agentid = 10 and active = 1 $cnt; // SELECT 25

PHP MySQLi Class Documentation, Release 1.0 26 Chapter 12. Properties sharing

CHAPTER 13 JOIN method $db->join( users u, p.tenantid=u.tenantid, LEFT ); $db->where( u.id, 6); $products = $db->get ( products p, null, u.name, p.productname ); print_r ($products); 27

PHP MySQLi Class Documentation, Release 1.0 28 Chapter 13. JOIN method

CHAPTER 14 Subqueries Subquery init Subquery init without an alias to use in inserts/updates/where Eg. (select * from users) $sq = $db->subquery(); $sq->get ( users ); A subquery with an alias specified to use in JOINs. Eg. (select * from users) sq $sq = $db->subquery( sq ); $sq->get ( users ); Subquery in selects: $ids = $db->subquery (); $ids->where ( qty, 2, > ); $ids->get ( products, null, userid ); $db->where ( id, $ids, in ); $res = $db->get ( users ); // Gives SELECT * FROM users WHERE id IN (SELECT userid FROM products WHERE qty > 2) Subquery in inserts: $useridq = $db->subquery (); $useridq->where ( id, 6); $useridq->getone ( users, name ), $data = Array ( productname => test product, userid => $useridq, lastupdated => $db->now() ); $id = $db->insert ( products, $data); // Gives INSERT INTO PRODUCTS (productname, userid, lastupdated) values ( test product, (SELECT name FROM users WHERE id = 6), NOW()); Subquery in joins: $usersq = $db->subquery ( u ); $usersq->where ( active, 1); $usersq->get ( users ); $db->join($usersq, p.userid=u.id, LEFT ); $products = $db->get ( products p, null, u.login, p.productname ); print_r ($products); // SELECT u.login, p.productname FROM products p LEFT JOIN (SELECT * FROM t_users WHERE active = 1) u on p.userid=u.id; 29

PHP MySQLi Class Documentation, Release 1.0 30 Chapter 14. Subqueries

CHAPTER 15 EXISTS / NOT EXISTS condition $sub = $db->subquery(); $sub->where( company, testcompany ); $sub->get ( users, null, userid ); $db->where (null, $sub, exists ); $products = $db->get ( products ); // Gives SELECT * FROM products WHERE EXISTS (select userid from users where company= testcompany ) 31

PHP MySQLi Class Documentation, Release 1.0 32 Chapter 15. EXISTS / NOT EXISTS condition

CHAPTER 16 Has method A convenient function that returns TRUE if exists at least an element that satisfy the where condition specified calling the where method before this one. $db->where( user, $user); $db->where( password, md5($password)); if($db->has( users )) { return You are logged ; } else { return Wrong user/password ; } 33

PHP MySQLi Class Documentation, Release 1.0 34 Chapter 16. Has method

CHAPTER 17 Helper methods Reconnect in case mysql connection died: if (!$db->ping()) $db->connect() Get last executed SQL query: Please note that function returns SQL query only for debugging purposes as its execution most likely will fail due missing quotes around char variables. $db->get( users ); echo Last executed query was. $db->getlastquery(); Check if table exists: if ($db->tableexists ( users )) echo hooray ; mysqli_real_escape_string() wrapper: $escaped = $db->escape ( and 1=1 ); 35

PHP MySQLi Class Documentation, Release 1.0 36 Chapter 17. Helper methods

CHAPTER 18 Transaction helpers Please keep in mind that transactions are working on innodb tables. Rollback transaction if insert fails: $db->starttransaction();... if (!$db->insert ( mytable, $insertdata)) { //Error while saving, cancel new record $db->rollback(); } else { //OK $db->commit(); } 37

PHP MySQLi Class Documentation, Release 1.0 38 Chapter 18. Transaction helpers

CHAPTER 19 Query exectution time benchmarking To track query execution time settrace() function should be called. $db->settrace (true); // As a second parameter it is possible to define prefix of the path which should be striped from filename // $db->settrace (true, $_SERVER[ SERVER_ROOT ]); $db->get( users ); $db- >get( test ); print_r ($db->trace); [0] => Array ( [0] => SELECT * FROM t_users ORDER BY id ASC [1] => 0.0010669231414795 [2] => MysqliDb->get() >> file /avb/work/php-mysqli-database-class/tests.php line #151 ) [1] => Array ( [0] => SELECT * FROM t_test [1] => 0.00069189071655273 [2] => MysqliDb->get() >> file /avb/work/php-mysqli-database-class/tests.php line #152 ) 39

PHP MySQLi Class Documentation, Release 1.0 40 Chapter 19. Query exectution time benchmarking

CHAPTER 20 Indices and tables genindex modindex search 41