A little bit of what's been queried about PDO

Source: Internet
Author: User
Tags dsn error handling getmessage
1.PDO Introduction
PDO (PHP Data Object) is a new addition to PHP 5, a major feature of PHP 5, because before PHP 5 php4/php3 are a bunch of database extensions to the various database connections and processing, what Php_mysql.dll, Php_ Pgsql.dll, Php_mssql.dll, Php_sqlite.dll and so on.
PHP6 will also default to the use of PDO connection, MySQL extension will be used as a secondary
2.PDO Configuration
In the php.ini, remove the "Extension=php_pdo.dll" before the ";" Number, to connect to the database, you also need to remove the PDO-related database extensions before the ";" Number, and then restart the Apache server.
Extension=php_pdo.dll
Extension=php_pdo_mysql.dll
Extension=php_pdo_pgsql.dll
Extension=php_pdo_sqlite.dll
Extension=php_pdo_mssql.dll
Extension=php_pdo_odbc.dll
Extension=php_pdo_firebird.dll
......
3.PDO Connection MySQL Database
New PDO ("Mysql:host=localhost;dbname=db_demo", "Root", "");
The default is not a long connection, and to use a database long connection, you need to add the following parameters at the end:
New PDO ("Mysql:host=localhost;dbname=db_demo", "Root", "", "Array (pdo::attr_persistent => true)");
4.PDO common method and its application
Pdo::query () is used primarily for operations that have record results returned, especially select operations
Pdo::exec () is primarily for operations that are returned without a result set, such as INSERT, update, and so on
Pdo::lastinsertid () returns the last insert operation, the primary key column type is the final self-increasing ID
Pdostatement::fetch () is used to get a record
Pdostatement::fetchall () is to get all the recordset into one
5.PDO Operation MySQL Database instance




Copy code code as follows:




<?php
$pdo = new PDO ("Mysql:host=localhost;dbname=db_demo", "Root", "");
if ($pdo-> exec ("INSERT into Db_demo (name,content) VALUES (' title ', ' content ')") {
echo "Insert succeeded. ";
echo $pdo-> Lastinsertid ();
}
?>








Copy code code as follows:




<?php
$pdo = new PDO ("Mysql:host=localhost;dbname=db_demo", "Root", "");
$rs = $pdo-> Query ("SELECT * from Test");
while ($row = $rs-> fetch ()) {
Print_r ($row);
}
?>
































Why to speak PDO:


(1) The most used in the market, most enterprises use PDO


(2) mysqli only supports MySQL database, PDO supports most databases


(3) Future projects are implemented using PDO as a database abstraction layer


MYSQLI------is the consolidation of MySQL databases:


(pretreatment mechanism)


(Error handling mechanism)


(object-oriented programming Mode)


How PHP operates the database


Extensions to specific databases: PHP wants to operate that database, and it needs to be expanded to provide a function to manipulate the database.


Second, what is PDO


PDO is a MySQL official package, based on object-oriented programming ideas, the use of C language development of the database abstraction layer


Third, the concept of PDO database abstraction:


PDO abstract class


It's a class of encapsulation, a new way to control the database.


The specific operation of the database code encapsulated to the database abstraction layer, if the database transfer, just in the PHP code in the high-speed database abstraction layer, you go to use which database can be


PDO by code


<?php


Write a function that operates on a different database based on the parameters passed


function mysql_db ($type) {


if ($type = = ' MySQL ') {


Mysql_connect ();


mysql_select_db ();


}elseif ($type = = ' mssql ') {


Mssql_connect ();


Mssql_query ();


}elseif ($type = = ' Oracle ') {


function to manipulate a database specifically


}


}


mysql_db (' MySQL ');


function Mysql_q ($type, $sql) {


if ($type = = ' MySQL ') {


mysql_query ($sql);


}


}


?>


First, how to use PDO


and currently using MySQL very much like


To use MySQL, you need to open the MySQL extension,


To use PDO, you need to turn on the PDO extension


Get the PDO object and call the method


(1) to open PDO drive


Extension = Php_pdo.dll


Extension = Php_pdo_sqlite.dll


Extension = Php_pdo_mysql.dll


To open this extension (drive), you can use this extension to provide us with classes


(2) Use this class to instantiate this class, call properties and methods


<?php


Using PDO to manipulate the database


First parameter: The type of connection database: Host name, database name


$DSC = ' Mysql:host=localhost;dbname=mysql_text ';


$user = ' root ';


$pass = ' 123 ';


$pdo = new PDO ($DSC, $user, $pass);//When instantiating a class, the __construct () constructor is automatically invoked first


Var_dump ($PDO);





Execute SQL statement to get


$sql = ' select*fromgoods ';


$result = $pdo->query ($sql);//query method returns Pdostatement object


If you want to get specific data, you need to call the object's method: Fetchall (); The parameter is a class constant that indicates what data is returned


$rows = $result->fetchall (pdo::fetch_both);


Var_dump ($rows);





Update the operation of the database


$sql = ' Update goods set goods_name= ' Lalala ' wheregoods_id=3 ';


Execute the statement of additions and deletions, exec () method, execute Query statement query ()


EXEC () returns the affected function query () returns the Pdostatement object


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


Var_dump ($nums);





?>


Ii. PDO pre-compiling mechanism


Separate the data part of the SQL statement from the part of the fee data ———— and precompile the part without the data. Prepare () ———— on compiling results bind data Bandparam () ———— Execute compilation results execute ()


The benefits of precompilation: 1, reduce the number of compiled characters, the speed of the compilation increased


2. If you execute the same SQL statement again, bind the data directly, reduce the time of compiling SQL statements


Write code to implement PDO (and processing mechanism)


<?php


Pre-compiling: PDO::p repare ($sql); Returns the Pdostatement object


Binding Data Pdostamentt->bindparam (); Binding data to precompiled results


Perform compilation results pdostament->execute ();





Using PDO to manipulate the database


First parameter: The type of connection database: Host name, database name


$dsn = ' Mysql:host=localhost;dbname=mysql_text ';


$user = ' root ';


$pass = ' 123 ';


$pdo = new PDO ($DSN, $user, $pass);


Var_dump ($PDO);








Precompiled: Prepare (); parameter is an SQL statement without data


Replace the data portion of the SQL statement with a placeholder: placeholder name


$sql = ' Insert Intogoods values (null,:name,:p rice,:number) ';


$SMT = $pdo->prepare ($sql); Returns a Pdostament object


Binding Data Pdostament Object Bindparam () to bind parameters: placeholders, actual data


$goods _name= ' surface ';


$goods _price= ' 3500 ';


$goods _num= ' 41 ';


$smt->bindparam (': Name ', $goods _name);


$smt->bindparam (':p rice ', $goods _price);


$smt->bindparam (': Number ', $goods _num);


$smt->execute ();


?>


Third, the PDO error handling mechanism:


(1) Silent mode


The default is consistent with MySQL processing, not realistic error messages (silent mode) but we can get the error message in a fixed way


(2) Warning mode


Change property settings error handling mode


$pdo->setattribute (pdo::attr_errmode,pdo::errmode_warning);


(3) Exception mode, when an error occurs, an exception is thrown


$pdo->setattribute (pdo::attr_errmode,pdo::errmode_exception);


$sql = ' Select*fromgood ';


try {


Try code that might be wrong


$pdo->query ($sql);


}catch (Pdoexception $e) {


Now catch the exception, you look at the office, is to let him show it, or output to the log file.


Typically, the error message is exported to the log file.


Var_dump ($e->getmessage ());


File_put_contents (' D://mysql.log ', $e->getmessage ());


}

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.