MySQL, PDO objects

table of Contents

1, singleton

2, pdo and db

3, singleton get pdo

4, pdo achieve db CRUD

5, pdo exception handling exception

6, pdo prepare Pretreatment

7, pdo transaction transaction

8, examples of student management

1, singleton

Chinese name singleton singleton pattern, design pattern is a configuration class. Its purpose is to acquire the object of this class in the global time can always get to a unique object, rather than each instantiation creates a kind of class structure of the new object. Special operation in the DB, DB connected to the object which must be implemented by a single mode of embodiment.

class DBConnectionSingleton{

private static $ con = null; // declare through private static singleton object +

//function __construct(){}

public static function getcon(){

if (! self :: $ con) {// perform static characteristics guarantee a unique Object

self::$con = new self();

}

return self::$con;

}

}

$con1 = DBConnectionSingleton::getcon();

$con2 = DBConnectionSingleton::getcon();

2. pdo and db

Description: PDO data object i.e. PHP (PHP Data Object).

    PDO can be seen as a tool, this tool defines a lightweight, consistent interface to access the database for PHP.

    Each PDO database driver implements the interface characteristics of the particular database may be disclosed as a standard extension. 

Syntax: $ pdo = new PDO ( "DB name: host = hostname; dbname = DB name", "DB account", "DB password");

note:

    (1) using the PDO extension itself does not implement any database functionality,

        You must use a specific database of PDO driver to access the database service.

    (2) PDO provides a [] data access abstraction layer, which means that regardless of which database to use,

  You can use the same functions (methods) to query and retrieve data. 

    (3) PDO database abstraction layer is not provided, it will not overwrite the SQL, the analog characteristics will not deleted.

  If necessary, you should use a full-blown abstraction layer.

    (4) start from PHP 5.1 comes with a PDO, it is available as a PECL extension in PHP 5.0 in. 

  PDO requires PHP 5 core new features, and therefore will not run on older versions of PHP.

to sum up:

    PDO is like a gun, and what kind of database use is like to select a different bullets.

    No matter what kind of bullet features a method of firing a total no deviation, they are shot only.

Added: When connecting DB, not every connection can guarantee complete. Therefore, we must

    Set a "insurance" to help us monitor the situation connected, this thing is try ... catch mechanism.

    

   try{

$pdo  = new PDO("mysql:host=localhost;dbname=frankdb","root","");

   }catch(PDOException $e){

echo "Error";

echo $e->getMessage();

   }

 

   Throughout the try ... catch structure, try part of the code may appear abnormal.

   When the process of code that is executed once the try part of the code really happened exception, this exception will be thrown immediately, and execute code in the catch section.

   Shaped catch portion for receiving the reference $ E is thrown exception.

   

   It can be considered: the above structure is a fixed structure at the time of acquisition PDO!

3.singleton get pdo

Before saying this lesson content, we first determine what you both singleton and for PDO itself have already mastered to a certain extent, in other words I believe we are able to independently write PDO singleton and access code. If there is no objection, then let's use a question to elicit the content of this lesson:

Suppose there are two small A and small B people, two men are using PDO to access the DB. Then

(1) A small access all the data in DB through PDO, and delete them.

(2) small B DB access via PDO, and wherein a query of data.

If there is no way to determine who should small A and small B access DB, who after visiting DB, it will produce what results?

class PDOSingleton{

private static $pdo = null;

function __construct(){

if(!self::$pdo){

try{

$pdo  = new PDO("mysql:host=localhost;dbname=frankdb","root","");

}catch(PDOException $e){

echo $e->getMessage();

}

}

return self::$pdo;

}

// embodiment provides a single process to obtain a globally unique singleton object

public static function getpdo(){

if(!self::$pdo){

 try{

$pdo  = new PDO("mysql:host=localhost;dbname=frankdb","root","");

}catch(PDOException $e){

echo $e->getMessage();

}

}

return self::$pdo;

}

}

4.pdo achieve db CRUD

In the previous lesson we said, pdo [a] data access abstraction layer.

Essentially therefore the operation in the face of the same DB, pdo php operation and direct operation itself is no different.

require_once "PDOSingleton.php";

$ Pdo = PDOSingleton :: getpdo (); // get global singleton object single pdo Example

$ Pdo-> exec ( 'set names utf8'); // exec () method is executed pdo object,

   The equivalent query php () method.

 

$ Sql ​​= "insert into friendslist values ​​( 'Chicken great beauty', 222,222,2000001)";

//…

if ($ pdo-> exec ($ sql)) {// db operation performed by pdo

echo "success";

}else{

echo "error";

}

 

5.pdo exception handling exception

Exception handling Exception refers to processing means when an exception occurs in the try ... catch, the exception handling are usually thrown directly reminder. The setting means setting a reminder, there are three ways:

(1) default mode

ErrorCode errorInfo properties and depends on system implementation provided

(2) alarm mode:

为pdo设置setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);

(3) interrupt mode:

为pdo设置setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

Tips: Note that exception handling is not necessary to have a three models to show it explicitly, even if it does not take the initiative to write one kind will not be considered illegal. But actively implement exception handling can give us better tips when an exception occurs, it is recommended that if you add exception handling module as much as possible under the circumstances permit code.

try{

$pdo = new PDO("mysql:host=localhost;dbname=frankdb","root","");

//$pdo -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);

//$pdo -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

}catch(PDOExeption $e){

echo $e -> getMessage();

}

$sql = "insert into friendslist vales(321,'hah',30,1000200)";

$res = $pdo->exec($sql);

if($res){

echo "succes";

}

else{

echo $pdo -> errorCode();

echo $pdo -> errorInfo();

}

 

6.pdo pre-prepare

Is a statement in the pre-prepare operation pdo db provided. Its logic and normal language pdo access the same. But the difference is that prepare statement allows the user to set sql statement [in] and be part between injection and extraction operation parameters] [sql statement execution, rather than the normal pdo write directly access the same parameters dead.

(1) prepare () method and execute () method

(2) bindValue () method

(3) bindColumn () method

 

1) prepare * () method and execute () method

Description: a.prepare () method sql statement pretreatment method allows pdo pretreated semifinished] [sql statement.

And generating a result PDOStatementObject type.

    b.execute () method is provided to PDOSO type of object methods to perform the sql statement [finished]

And generating a result PDOStatementObject type.

Description:

    a. pdo handed over to prepare pre-treatment of semi-finished products] [sql statement, using the? question mark as a placeholder,

A parameter indicating the parameters to be transferred

    b.prepare pre-treatment must only deal with [semi-finished] sql statement, if it is complete you need to use the exec method execution

    c.execute () method allows an array as a parameter, the parameter to be brought into the sql statement pretreated,

And stores the result will PDOSO object.

    d.PDOSO objects have different meanings in different stages of pretreatment! ! Must not be confused, it must be determined according to the context.

grammar:

$sql = "insert into friendslist values(?,?,?,?)";

$pdoso= $pdo->prepare($sql);

echo $ pdoso-> execute (array ( "Fried Chicken great beauty", "female", 99,12345698701));

2) bindvalue () method

Description: bindValue () method is a method PDOSO objects used to provide pdo obtained after pretreatment,

    Sql statement [used to be] semi-finished products by value.

语法:$pdoso->bindValue(index,value);

Description:

    (1) The first parameter passed to the value of several parameters sql statement. The first write 1, and so on.

    (2) the second parameter corresponds to a specific parameter value passed in the sql statement.

    (3) bindValue time to bind a parameter, if there is more than you need to call multiple times.

example:

$sql = "insert into friendslist values(?,?,?,?)";

$pdoso = $pdo->prepare($sql);

$ Pdoso-> bindValue (1, 'fried chicken fried chicken great beauty');

$pdoso->bindValue(2,'female');

$pdoso->bindValue(3,666);

$pdoso->bindValue(4,1322321123);

echo $pdoso->execute();

3) bindcolumn () method

Description: bindColumn () method allows to bind an execution result data to a specified object,

    This method requires performing after execute () method is executed.

Syntax: $ pdoso-> bindColumn (index, specified variable);

Description:

    (1) The first parameter indicates the result of the data columns. The first column write 1, and so on.

    (2) The second parameter represents the data to be assigned to that variable, a random variable.

    (3) bindColumn () method once a binding to a variable. For more binding, it can be executed multiple times.

example:

    $sql = "select * from friendslist";

    $pdoso = $pdo -> prepare($sql);

    $pdoso -> execute();

    $pdoso -> bindColumn(1,$friendsName);

    $pdoso -> bindColumn(2,$friendsSex);

    while($row = $pdoso->fetch(PDO::FETCH_COLUMN)){

echo "{$friendsName}"."----"."{$friendsSex}"."<br/>";

    }

7.pdo transaction transaction

Affairs: structure composed of multiple events.

Event: Event is actually execute pre-sentence statement execution. 

note:

(1) the entire transaction operation must try ... catch put, this is because we can not guarantee the execution of the event with some success.

    And for the entire transaction, any failure will lead to catch an event trigger.

    The catch trigger means that all operations must be made before the reduction must

    Rollback: $ pdo-> rollBack ()

 

(2) the operating statement must be executed after the transaction open, stopped before the transaction commits.

    Open Transaction: $ pdo-> beginTransaction ();

    Close Transaction: $ pdo-> commit ();

 

(3) Chinese treatment options (avoid garbled):

    Read: $ pdo -> query ( "set names utf8"); 

    Insert: $ pdo -> exec ( 'set names utf8');

require_once "PDOSingleton.php";

$pdo = PDOSingleton::getpdo();

$pdo->query('set names utf8');

$pdo->exec('set names utf8');

try{

$pdo->beginTransaction();

$sql = "update friendslist set friendsPhoneNumber=? where friendsName=?";

$pdoso = $pdo->prepare($sql);

 

$ Pdoso-> execute (array (999, 'Fried Chicken Fried Chicken great beauty')); // Success

$ Pdoso-> execute (array (777)); // fail, does not match the parameters

 

echo $pdo->commit();

}catch (PDOException $e){

$pdo -> rollBack();

echo "failure";

}

 

Guess you like

Origin www.cnblogs.com/Jiang-jiang936098227/p/11605432.html