Here is a brief introduction to the use of the database abstraction layer PDO:
PDO (PHP Data Objects) is a lightweight PHP extension that provides a data access abstraction layer. The PDO is only available in PHP5.0 above version.
Here's a brief introduction to the predefined constants commonly used by PDO:
PDO::P aram_bool (integer) represents a Boolean data type
PDO::P aram_null (integer) represents a SQL with a data type of NULL
PDO::P aram_int (integer) represented as an integer data type SQL
PDO::P aram_str (Integer) SQL representing a data type of char varchar or other string
PDO::P aram_lob (integer) A SQL that represents an object data type
Pdo::fetch_lazy (integer), you 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) takes the next row of the result set
pdo::fetch_ori_prior (integer) to take the previous row of the result set
pdo::fetch_ori_first (integer) takes the first row of the result set
pdo::fetch_ori_last (integer) takes the last row of the result set
pdo::attr_persistent (integer) to create a persistent connection, rather than creating a new connection
Basic usage of PDO:
Use PDO to connect to the database (use MySQL here only):
Copy Code code as follows:
<?php
$DBH = new PDO (' Mysql:host=localhost;dbname=test ', $user, $pass);
?>
The following code is for handling MySQL connection errors:
Copy Code code 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 ();
}
?>
Here are two examples of repeating INSERT statements:
Copy Code code 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 Code code 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 operations on the database:
Copy Code code as follows:
<?php
$stmt = $dbh->prepare ("select * from REGISTRY where name =?");
if ($stmt->execute (Array ($_get[' name '))) {
while ($row = $stmt->fetch ()) {
Print_r ($row);
}
}
?>