[轉]PDO知识

轉自 : http://apps.hi.baidu.com/share/detail/50250843#content

例 1654. Connecting to MySQL
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
 
例 1655. Handling connection errors
<?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();
}
?>
 
例 1656. Closing a connection
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here

// and now we're done; close it
$dbh = null;
?>

例 1657. Persistent connections
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
   PDO::ATTR_PERSISTENT => true
));
?>
 
例 1658. Executing a batch in a transaction
<?php
try {
   $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
   array(PDO::ATTR_PERSISTENT => true));
   echo "Connected\n";
   $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $dbh->beginTransaction();
   $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
   $dbh->exec("insert into salarychange (id, amount, changedate)
   values (23, 50000, NOW())");
   $dbh->commit();
  
} catch (Exception $e) {
   $dbh->rollBack();
   echo "Failed: " . $e->getMessage();
}
?>
例 1659. Repeated inserts using prepared statements
This example performs an INSERT query by substituting a name and a value for the named placeholders.
<?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();
?>
 
 
例 1660. Repeated inserts using prepared statements
This example performs an INSERT query by substituting a name and a value for the positional ? placeholders.
<?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();
?>
 
例 1661. Fetching data using prepared statements
This example fetches data based on a key value supplied by a form. The user input is automatically quoted, so there is no risk of a SQL injection attack.
<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
   while ($row = $stmt->fetch()) {
print_r($row);
   }
}
?>
 
 
例 1662. Calling a stored procedure with an output parameter
<?php
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $return_value\n";
?>
 

例 1663. Calling a stored procedure with an input/output parameter
<?php
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
?>


例 1664. Invalid use of placeholder
<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE '%?%'");
$stmt->execute(array($_GET['name']));
// placeholder must be used in the place of the whole value
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->execute(array("%$_GET[name]%"));
?>
 
例 1665. Displaying an image from a database
This example binds the LOB into the variable named $lob and then sends it to the browser using fpassthru(). Since the LOB is represented as a stream, functions such as fgets(), fread() and stream_get_contents() can be used on it.
<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
header("Content-Type: $type");
fpassthru($lob);
?>


例 1666. Inserting an image into a database
This example opens up a file and passes the file handle to PDO to insert it as a LOB. PDO will do its best to get the contents of the file up to the database in the most efficient manner possible.
<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // some function to allocate a new ID
// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation
$fp = fopen($_FILES['file']['tmp_name'], 'rb');
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);
$db->beginTransaction();
$stmt->execute();
$db->commit();
?>


例 1667. Inserting an image into a database: Oracle
Oracle requires a slightly different syntax for inserting a lob from a file. It's also essential that you perform the insert under a transaction, otherwise your newly inserted LOB will be committed with a zero-length as part of the implicit commit that happens when the query is executed:
<?php
$db = new PDO('oci:', 'scott', 'tiger');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) " .
   "VALUES (?, ?, EMPTY_BLOB()) RETURNING imagedata INTO ?");
$id = get_new_id(); // some function to allocate a new ID
// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation
$fp = fopen($_FILES['file']['tmp_name'], 'rb');
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);
$stmt->beginTransaction();
$stmt->execute();
$stmt->commit();
?>
 
例 1668. The PDOException class
<?php
class PDOException extends Exception
{
public $errorInfo = null; // corresponds to PDO::errorInfo()
                              // or PDOStatement::errorInfo()
protected $message;       // textual error message
                              // use Exception::getMessage() to access it
protected $code;          // SQLSTATE error code
                              // use Exception::getCode() to access it
}
?>
例 1669. using PDO::ATTR_DRIVER_NAME
<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
   echo "Running on mysql; doing something mysql specific here\n";
}
?>
 
參考資料:
原文地址:https://www.cnblogs.com/Athrun/p/pdo.html