Home  >  Article  >  Backend Development  >  Detailed explanation of PHP5 PDO connection to database_PHP tutorial

Detailed explanation of PHP5 PDO connection to database_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:41:13803browse

This article introduces PHP5 PDO to connect to the database
1. Introduction to PDO
PDO (PHP Data Object) is something added in PHP 5. It is a major new feature added in PHP 5, because in PHP 5 In the past, php4/php3 had a bunch of database extensions to connect and process each database, such as php_mysql.dll, php_pgsql.dll, php_mssql.dll, php_sqlite.dll, etc.
PHP6 will also use PDO to connect by default, and the mysql extension will be used as an auxiliary

2. PDO configuration
In PHP.ini, remove "extension=php_pdo. dll". If you want to connect to the database, you also need to remove the ";" sign in front of the database extension related to PDO, 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 connects to mysql database
new PDO("mysql:host=localhost;dbname=db_demo" ,"root","");
The default is not a long connection. If you want to use a long connection to the database, 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. Common PDO methods and their applications
PDO::query() Mainly used for operations that return recorded results, especially SELECT operations
PDO::exec() Mainly used for operations that do not return a result set, such as INSERT, UPDATE and other operations
PDO::lastInsertId() returns In the last insertion operation, the primary key column type is the last auto-incremented ID
PDOStatement::fetch() is used to get a record
PDOStatement::fetchAll() is used to get all the record sets into one

5. PDO operates MYSQL database instance
$pdo = new PDO("mysql:host=localhost;dbname=db_demo","root", "");
if($pdo -> exec("insert into db_demo(name,content) values(title,content)")){
echo "Insertion successful!";
echo $ pdo -> lastinsertid();
}
?>
$pdo = new PDO("mysql:host=localhost;dbname=db_demo","root", "");
$rs = $pdo -> query("select * from test");
while($row = $rs -> fetch()){
print_r($row );
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486143.htmlTechArticleThis article introduces PHP5 PDO to connect to the database 1. Introduction to PDO PDO (PHP Data Object) is something added in PHP 5. It is a major new feature added to PHP 5, because before PHP 5, php4/php3 were all...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn