Helper classes for the encapsulated PDO operations database Mysqlhelper

Source: Internet
Author: User
Tags dsn exception handling getmessage

Helper classes for the encapsulated PDO operations database Mysqlhelper

The Help class for the encapsulated PDO operations database is Mysqlhelper, and is only for learning and communication use!

<?php/** * Description of Mysqlhelper * * @author fx678 */class Mysqlhelper {private static $pdoDB = null;    Public Function __destruct () {$this->pdodb = null; }/** * Gets the PDO connection information in the INI configuration file and returns the PDO object * $section: Database Configuration node * Return PDO object **/private static Functio N Getpdodb ($section = "db") {if (self:: $pdoDB!== null &&!array_key_exists ($section, Array (' DSN ', ' username ', '            Password ')) {if (!array_key_exists ($section, Self:: $pdoDB)) {Return to self:: $pdoDB;        }} $config = Config::getconfig ($section);                     try {self:: $pdoDB = new PDO ($config [' DSN '], $config [' username '],            $config [' Password '], array (pdo::mysql_attr_init_command = "SET NAMES ' UTF8 ';")            );        } catch (Exception $ex) {throw new Exception (' DB connection error: '. $ex->getmessage ()); }                Return self:: $pdoDB;     /** * Execute Query statement without parameters * $connectionString: Database configuration information node * $STRSQL: T-SQL statement to execute * return Pdostatement object **/public static function query ($connectionString, $STRSQL) {try {$statement = Self::getpdodb ($con                      nectionstring)->query ($STRSQL, PDO::FETCH_ASSOC);           if ($statement = = = False) {throw new Exception ($this->getdb ($connectionString)->errorinfo ());        }} catch (Exception $ex) {throw new Execption ($ex->getmessage ());     } return $statement; /** * Execute query statement with parameters * $connectionString: Database configuration information node * $STRSQL: T-SQL statement to execute * $PARAMARR: Parameter array * return P            Dostatement object **/public static function Queryparam ($connectionString, $STRSQL, $PARAMARR) {try {                        $statement = Self::getpdodb ($connectionString)->prepare ($STRSQL); Gets the corresponding parameter if (Isset ($PARAMARR) &&amP Is_array ($PARAMARR)) {foreach ($paramArr as $key = = $val) {$statement->bindparam (                "$key", $val [0], $val [1]);            }}//Execute $statement->execute ();        } catch (Exception $ex) {throw new Execption ($ex->getmessage ()); } if ($statement = = = False) {throw new Exception ($this->getdb ($connectionString)->errorinfo        ());    } return $statement; }/** * Executes the (add-on) statement with parameters and uses the thing mechanism * $connectionString: Database configuration information node * $STRSQL: T-SQL statement to execute * $PARAMARR: Reference         Number Array * Returns the number of rows affected (int) **/public static function Prepareparamtransaction ($connectionString, $STRSQL, $PARAMARR) {                $count = 0;            try {$pdo = Self::getpdodb ($connectionString);            Turn off Auto-commit (default is autocommit) $pdo->setattribute (pdo::attr_autocommit, 0); Turn on exception handling $pdo-SetAttribute (PDO::attr_errmode, pdo::errmode_exception);                        Start things $pdo-BeginTransaction ();                                       Gets the Statement object $statement = $pdo->prepare ($STRSQL);  Get the corresponding parameter if (Isset ($PARAMARR) && Is_array ($PARAMARR)) {foreach ($paramArr as $key =                  $val) {$statement->bindparam ("$key", $val [0], $val [1]);            }}//Execute $statement, execute ();                        $count = (int) ($statement, RowCount ());        Commit a thing $pdo, commit ();        } catch (Exception $ex) {throw new Execption ($ex->getmessage ()); } if ($statement = = = False) {throw new Exception ($this->getpdodb ($connectionString)->errori        NFO ());    }//Returns the number of rows affected return $count; }}?>
Call Reference Example 1:

$STRSQL = "SELECT * from Newsindex n WHERE N. ' Id ' =:id LIMIT 1;";                $PARAMARR = Array (            ': Id ' = = Array ($Id,  PDO::P aram_int)        );                foreach (Self::queryparam (self: $connectionString, $STRSQL, $PARAMARR) as $row) {            $model = new Htnewsindex ();            Htnewsindexmapper::map ($model, $row);            return $model;        }                return null;
Call Reference Example 2:
$STRSQL = "INSERT into News_index (bsid,idx_period,previous_price,actual_price,revised_price,survey_price,publish_ Time,create_time,status) "       ." VALUES (: Bsid,:idxperiod,:P reviousprice,:actualprice,:revisedprice,:surveyprice,:P ublishtime,:createtime,:                Status); "; The parameter array $params = Array (': bsid ' = = Array ($model->getbsid (), PDO::P aram_str), ' : idxperiod ' = = Array ($model->getidxperiod (), PDO::P aram_str), ':P reviousprice ' = = Array ($model-&G T;getpreviousprice (), PDO::P aram_str), ': actualprice ' = = Array ($model->getactualprice (), PDO::P aram_str) , ': revisedprice ' = = Array ($model->getrevisedprice (), PDO::P aram_str), ': Surveyprice ' =&gt ; Array ($model->getsurveyprice (), PDO::P aram_str), ':P ublishtime ' = = Array ($model->getpublishtime (), PD O::P aram_str), ': createtime ' = = Array ($model->getcreatetime (), PDO::P aram_str), ': Status ' = = Array ($model->getstatus (), PDO::P aram_int));        try {return (int) Self::p repareparamtransaction (self:: $connectionString, $STRSQL, $params);        } catch (Exception $ex) {throw new Exception ($ex->gettraceasstring ()); }


Because of the limited understanding, the shortcomings please give more advice!
In this process, I found that using PDO parametric fuzzy query, there is always no result, no exception thrown, the following statement:

SELECT * from NEWS n WHERE N. ' Title ' like ('%:key% ');
SELECT * from NEWS n WHERE N. ' Title ' like ('%?% ');
This parameterized fuzzy query always has no results. Please enlighten the person who knows!


Helper classes for the encapsulated PDO operations database Mysqlhelper

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.