Common PDO class library instance analysis in PHP and pdo class library instance Analysis _ PHP Tutorial

Source: Internet
Author: User
Tags php database
Common PDO class library instance analysis in PHP and pdo class library instance analysis. Examples of common PDO class libraries in PHP are analyzed. Examples of pdo class libraries in PHP are described in this article. I would like to share with you for your reference, as shown below: 1. Analysis of common PDO class libraries used by Db. class. php to connect to the database PHP, and analysis of pdo class library instances

This article describes the common PDO class libraries of PHP. We will share this with you for your reference. The details are as follows:

1. connect Db. class. php to the database

<? Php // connect to the database class Db {static public function getDB () {try {$ pdo = new PDO (DB_DSN, DB_USER, DB_PWD); $ pdo-> setAttribute (PDO :: ATTR_PERSISTENT, true); // Set the database connection to persistent connection $ pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION ); // Set the throw error $ pdo-> setAttribute (PDO: ATTR_ORACLE_NULLS, true ); // SET when the string is empty to SQL NULL $ pdo-> query ('set NAMES utf8'); // SET Database encoding} catch (PDOException $ e) {exit ('database connection error, error Information: '. $ e-> getMessage () ;}return $ pdo ;}}?>

2. Model. class. php database operation class

<? Php/*** database operation Class Library * author Lee. * Last modify $ Date:; 04 $ */class M {private $ _ db; // database handle public $ _ SQL; // SQL statement/*** constructor */public function _ construct () {$ this-> _ db = Db: getDB ();} /*** database addition operation ** @ param string $ tName table name * @ param array $ field array * @ param array $ val value array * @ param bool $ is_lastInsertId whether to return adding ID * @ return int: whether the return result is successful by default, $ is_lastInsertId is true, and the add ID */public function is returned. Insert ($ tName, $ fields, $ vals, $ is_lastInsertId = FALSE) {try {if (! Is_array ($ fields) |! Is_array ($ vals) exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ fields = $ this-> formatArr ($ fields ); $ vals = $ this-> formatArr ($ vals, false); $ tName = $ this-> formatTabName ($ tName ); $ this-> _ SQL = "INSERT INTO {$ tName} ({$ fields}) VALUES ({$ vals})"; if (! $ Is_lastInsertId) {$ row = $ this-> _ db-> exec ($ this-> _ SQL); return $ row ;} else {$ this-> _ db-> exec ($ this-> _ SQL); $ lastId = (int) $ this-> _ db-> lastInsertId (); return $ lastId ;}} catch (PDOException $ e) {exit ($ e-> getMessage ());}} /*** database modification operation ** @ param string $ tName table name * @ param array $ field array * @ param array $ val value array * @ param string $ condition *@ return int number of affected rows */public function update ($ tNam E, $ fieldVal, $ condition) {try {if (! Is_array ($ fieldVal) |! Is_string ($ tName) |! Is_string ($ condition) exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ tName = $ this-> formatTabName ($ tName ); $ upStr = ''; foreach ($ fieldVal as $ k => $ v) {$ upStr. = '''. $ k. ''= '. '\''. $ v. '\''. ',';} $ upStr = rtrim ($ upStr ,','); $ this-> _ SQL = "UPDATE {$ tName} SET {$ upStr} WHERE {$ condition }"; $ row = $ this-> _ db-> exec ($ this-> _ SQL); return $ row;} catch (PDOException $ e) {exit ($ e-> getMessage ()) ;}/*** Delete a database (note: The where condition must be added) * @ param string $ tName table name * @ param string $ condition * @ return int number of affected rows */public function del ($ tName, $ condition) {try {if (! Is_string ($ tName) |! Is_string ($ condition) exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ tName = $ this-> formatTabName ($ tName ); $ this-> _ SQL = "DELETE FROM {$ tName} WHERE {$ condition }"; $ row = $ this-> _ db-> exec ($ this-> _ SQL); return $ row;} catch (PDOException $ e) {exit ($ e-> getMessage ());}} /*** total number of returned Tables * @ param string $ tName table name * @ param string $ condition * @ return int */public function total ($ tName, $ condition ='') {Try {if (! Is_string ($ tName) exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ tName = $ this-> formatTabName ($ tName ); $ this-> _ SQL = "SELECT COUNT (*) AS total FROM {$ tName }". ($ condition = ''? '': 'Where '. $ condition); $ re = $ this-> _ db-> query ($ this-> _ SQL); foreach ($ re as $ v) {$ total = $ v ['total'];} return (int) $ total;} catch (PDOException $ e) {exit ($ e-> getMessage ());}} /*** delete multiple data records in the database * @ param string $ tName table name * @ param string $ field dependent field * @ param array $ ids delete array * @ return int number of affected rows */public function delMulti ($ tName, $ field, $ ids) {try {if (! Is_string ($ tName) |! Is_array ($ ids) exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ delStr = ''; $ tName = $ this-> formatTabName ($ tName); $ field = $ this-> formatTabName ($ field); foreach ($ ids as $ v) {$ delStr. = $ v. ',';} $ delStr = rtrim ($ delStr ,','); $ this-> _ SQL = "DELETE FROM {$ tName} WHERE {$ field} IN ({$ delStr })"; $ row = $ this-> _ db-> exec ($ this-> _ SQL); return $ row;} catch (PDOException $ e) {exit ($ e-> getMessage ()) ;}/*** Get the last primary key of the table (Note: For INT type) * @ param string $ tName table name * @ return int */public function insertId ($ tName) {try {if (! Is_string ($ tName) exit ($ this-> getError (_ FUNCTION __, _ LINE __)); $ this-> _ SQL = "SHOW TABLE STATUS LIKE '{$ tName }'"; $ result = $ this-> _ db-> query ($ this-> _ SQL); $ insert_id = 0; foreach ($ result as $ v) {$ insert_id = $ v ['auto _ increment '];} return (int) $ insert_id;} catch (PDOException $ e) {exit ($ e-> getMessage () ;}/ *** check whether the data already exists (dependency condition) * @ param string $ tName table name * @ param string $ field dependent field * @ re Turn bool */public function exists ($ tName, $ condition) {try {if (! Is_string ($ tName) |! Is_string ($ condition) exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ tName = $ this-> formatTabName ($ tName ); $ this-> _ SQL = "SELECT COUNT (*) AS total FROM {$ tName} WHERE {$ condition }"; $ result = $ this-> _ db-> query ($ this-> _ SQL); foreach ($ result as $ v) {$ B = $ v ['total'];} if ($ B) {return true;} else {return false ;}} catch (PDOException $ e) {exit ($ e-> getMessage () ;}/ *** check whether the data already exists (depending on the INT master Key) * @ param string $ tName table name * @ param string $ primary Key * @ param int $ id primary key value * @ return bool */public function existsByPK ($ tName, $ primary, $ id) {try {if (! Is_string ($ tName) |! Is_string ($ primary) |! Is_int ($ id) exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ tName = $ this-> formatTabName ($ tName ); $ this-> _ SQL = "SELECT COUNT (*) AS total FROM {$ tName} WHERE {$ primary} = ". $ id; $ result = $ this-> _ db-> query ($ this-> _ SQL); foreach ($ result as $ v) {$ B = $ v ['total'];} if ($ B) {return true;} else {return false ;}} catch (PDOException $ e) {exit ($ e-> getMessage () ;}/ *** pre-delete (note: for primary keys of the INT type, we recommend that you Use) * @ param string $ tName table name * @ param string $ primary key field * @ param int or array or string $ ids to delete an INT and array, delete a string * @ return int to return the number of affected rows */public function delByPK ($ tName, $ primary, $ ids, $ mult = FALSE) {try {if (! Is_string ($ tName) |! Is_string ($ primary) | (! Is_int ($ ids )&&! Is_array ($ ids )&&! Is_string ($ ids) |! Is_bool ($ mult) exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ tName = $ this-> formatTabName ($ tName ); $ stmt = $ this-> _ db-> prepare ("delete from {$ tName} WHERE {$ primary} =? "); If (! $ Mult) {$ stmt-> bindParam (1, $ ids); $ row = $ stmt-> execute ();} else {if (is_array ($ ids )) {$ row = 0; foreach ($ ids as $ v) {$ stmt-> bindParam (1, $ v); if ($ stmt-> execute ()) {$ row ++ ;}}} elseif (is_string ($ ids) {if (! Strpos ($ ids, '-') exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ split = explode ('-', $ ids); if (count ($ split )! = 2 | $ split [0]> $ split [1]) exit ($ this-> getError (_ FUNCTION __, _ LINE __)); $ I = null; $ count = $ split [1]-$ split [0] + 1; for ($ I = 0; $ I <$ count; $ I ++) {$ idArr [$ I] = $ split [0] ++;} $ idStr = ''; foreach ($ idArr as $ id) {$ idStr. = $ id. ',';} $ idStr = rtrim ($ idStr ,','); $ this-> _ SQL = "DELETE FROM {$ tName} WHERE {$ primary} in ({$ idStr })"; $ row = $ this-> _ db-> exec ($ this-> _ SQL) ;}return $ row;} catch (PDO Exception $ e) {exit ($ e-> getMessage ());}} /*** return single field data or single record * @ param string $ tName table name * @ param string $ condition * @ param string or field returned by array $ fields, the default value is ** @ return string | array */public function getRow ($ tName, $ condition = '', $ fields =" * ") {try {if (! Is_string ($ tName) |! Is_string ($ condition) |! Is_string ($ fields) | empty ($ fields) exit ($ this-> getError (_ FUNCTION __, _ LINE __)); $ tName = $ this-> formatTabName ($ tName); $ this-> _ SQL = "SELECT {$ fields} FROM {$ tName}"; $ this-> _ SQL. = ($ condition = ''? '':" WHERE {$ condition }"). "LIMIT 1"; $ Something = $ this-> _ db-> prepare ($ this-> _ SQL); $ Something-> execute (); $ result = $ Something-> fetch (PDO: FETCH_ASSOC); if ($ fields = '*') {return $ result ;} else {return $ result [$ fields] ;}} catch (PDOException $ e) {exit ($ e-> getMessage ());}} /*** return multiple data records * @ param string $ tName table name * @ param string $ Field returned by fields, the default value is ** @ param string $ condition * @ param string $ order. * @ Param string $ limit display count * @ return PDOStatement */public function getAll ($ tName, $ fields = '*', $ condition = '', $ order = '', $ limit = '') {try {if (! Is_string ($ tName) |! Is_string ($ fields) |! Is_string ($ condition) |! Is_string ($ order) |! Is_string ($ limit) exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ tName = $ this-> formatTabName ($ tName ); $ fields = ($ fields = '*' | $ fields = '')? '*': $ Fields; $ condition = ''? '':" WHERE ". $ condition; $ order = ''? '':" Order by ". $ order; $ limit = ''? '':" LIMIT ". $ limit; $ this-> _ SQL = "SELECT {$ fields} FROM {$ tName} {$ condition} {$ order} {$ limit }"; $ things = $ this-> _ db-> prepare ($ this-> _ SQL); $ things-> execute (); $ result = $ things-> fetchAll (PDO:: FETCH_ASSOC); return $ result;} catch (PDOException $ e) {exit ($ e-> getMessage () ;}/ *** format the array (table structure and value) * @ param array $ field * @ param bool $ isField * @ return string */private function formatArr ($ field, $ isF Ield = TRUE) {if (! Is_array ($ field) exit ($ this-> getError (_ FUNCTION __, _ LINE _); $ fields = ''; if ($ isField) {foreach ($ field as $ v) {$ fields. = '''. $ v. '', ';}} else {foreach ($ field as $ v) {$ fields. = '\''. $ v. '\''. ',' ;}$ fields = rtrim ($ fields, ','); return $ fields ;} /*** format question mark ** @ param int $ count quantity * @ return string returns the formatted string */private function formatMark ($ count) {$ str = ''; if (! Is_int ($ count) exit ($ this-> getError (_ FUNCTION __, _ LINE _); if ($ count = 1) return '? '; For ($ I = 0; $ I <$ count; $ I ++) {$ str. = '?, ';} Return rtrim ($ str,', ');}/*** error message * @ param string $ fun * @ return string */private function getError ($ fun, $ line) {return _ CLASS __. '-> '. $ fun. '() line '. $ line. 'error! ';}/*** Processing table name * @ param string $ tName * @ return string */private function formatTabName ($ tName) {return '''. trim ($ tName ,'''). ''';}/*** destructor */public function _ destruct () {$ this-> _ db = null ;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.