PHP5 USES PDO to connect to a database

  • 2020-03-31 21:01:21
  • OfStack

1. Introduction to the PDO
PDO(PHP Data Object) is PHP 5 added things, is a new PHP 5 added a major function, because before PHP 5 php4/php3 is a pile of database extensions to connect with each database and processing, what php_mysql.dll, php_pgsql.dll, php_mssql.dll, php_sqlite.
PHP6 will also be connected by default using PDO, with the mysql extension being used as an aid
2. The PDO configuration
In php.ini, remove the ";" before "extension= php_pdd.dll" To connect to the database, you also need to remove the ";" before the database extension associated with PDO Then restart the Apache server.
The extension = php_pdo. DLL
The extension = php_pdo_mysql. DLL
The extension = php_pdo_pgsql. DLL
The extension = php_pdo_sqlite. DLL
The extension = php_pdo_mssql. DLL
The extension = php_pdo_odbc. DLL
The extension = php_pdo_firebird. DLL
.
3.PDO connection to mysql database
New PDO (" mysql: host = localhost; Dbname = db_demo ", "root", "");
The default is not a long connection. To use the database long connection, add the following parameters at the end:
New PDO (" mysql: host = localhost; Dbname = db_demo ", "root", ""," array (PDO: : ATTR_PERSISTENT = > True) ");
4. Common methods of PDO and their applications
PDO::query() is primarily used for operations that return recorded results, especially SELECT operations
PDO::exec() is primarily for operations that do not return a result set, such as INSERT, UPDATE, and so on
PDO::lastInsertId() returns the last insert operation, and the primary key column type is the last self-increment ID of the self-increment
PDOStatement::fetch() is used to fetch a record
PDOStatement::fetchAll() gets all the recordsets into one
5.PDO operates MYSQL database instance

 
<?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 successful! "; 
echo $pdo -> lastinsertid(); 
} 
?> 


 
<?php 
$pdo = new PDO("mysql:host=localhost;dbname=db_demo","root",""); 
$rs = $pdo -> query("select * from test"); 
while($row = $rs -> fetch()){ 
print_r($row); 
} 
?> 


Related articles: