The following describes how to use the database abstraction layer PDO:
PDO (PHP Data ObjectsIs a lightweight PHP extension that provides a data access abstraction layer. Also, PDO can only be used in PHP5.0 or later versions.
The following describes the predefined constants commonly used by PDO:
PDO: PARAM_BOOL(Integer) indicates the boolean data type.
PDO: PARAM_NULL(Integer) SQL statement that indicates NULL data type
PDO: PARAM_INT(Integer) indicates an SQL statement of the integer data type.
PDO: PARAM_STR(Integer) indicates an SQL statement of the Data Type of char varchar or other strings.
PDO: PARAM_LOB(Integer) indicates the SQL statement of the object data type.
PDO: FETCH_LAZY(Integer) the specified acquisition method should return each row of the result set as the variable name of an object, corresponding to its field name.
PDO: FETCH_ORI_NEXT(Integer)Returns the next row of the result set.
PDO: FETCH_ORI_PRIOR(Integer)Get the row before the result set
PDO: FETCH_ORI_FIRST(Integer)The first row of the result set.
PDO: FETCH_ORI_LAST(Integer)Returns the last row of the result set.
PDO: ATTR_PERSISTENT(Integer) create a persistent connection instead of creating a new connection.
Basic usage of PDO:
Use PDO to connect to the database (MySQL only ):Copy codeThe Code is as follows: <? Php
$ Dbh = new PDO ('mysql: host = localhost; dbname = test', $ user, $ pass );
?>
The following code is used to handle MySQL connection errors:Copy codeThe Code is as follows: <? Php
Try {
$ Dbh = new PDO ('mysql: host = localhost; dbname = test', $ user, $ pass );
Foreach ($ dbh-> query ('select * from foo') as $ row ){
Print_r ($ row );
}
$ Dbh = null;
} Catch (PDOException $ e ){
Print "Error! : ". $ E-> getMessage ()." <br/> ";
Die ();
}
?>
The following are two examples of repeated insert statements:Copy codeThe Code is as follows: <? Php
$ Stmt = $ dbh-> prepare ("insert into registry (name, value) VALUES (: name,: value )");
$ Stmt-> bindParam (': name', $ name );
$ Stmt-> bindParam (': value', $ value );
// Insert one row
$ Name = 'one ';
$ Value = 1;
$ Stmt-> execute ();
// Insert another row with different values
$ Name = 'two ';
$ Value = 2;
$ Stmt-> execute ();
?>
Copy codeThe Code is as follows: <? Php
$ Stmt = $ dbh-> prepare ("insert into registry (name, value) VALUES (?, ?) ");
$ Stmt-> bindParam (1, $ name );
$ Stmt-> bindParam (2, $ value );
// Insert one row
$ Name = 'one ';
$ Value = 1;
$ Stmt-> execute ();
// Insert another row with different values
$ Name = 'two ';
$ Value = 2;
$ Stmt-> execute ();
?>
Query a database:Copy codeThe Code is as follows: <? Php
$ Stmt = $ dbh-> prepare ("SELECT * from registry where name =? ");
If ($ stmt-> execute (array ($ _ GET ['name']) {
While ($ row = $ stmt-> fetch ()){
Print_r ($ row );
}
}
?>