这篇文章主要介绍了关于php的PDO操作,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
PHP 数据对象
简介
安装/配置
需求
安装
运行时配置
资源类型
预定义常量
连接与连接管理
事务与自动提交
预处理语句与存储过程
错误与错误处理
大对象
PDO — PDO 类
PDO::beginTransaction — 启动一个事务
PDO::commit — 提交一个事务
PDO::__construct — 创建一个表示数据库连接的 PDO 实例
PDO::errorCode — 获取跟数据库句柄上一次操作相关的 SQLSTATE
PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
PDO::exec — 执行一条 SQL 语句 , 并返回受影响的行数
PDO::getAttribute — 取回一个数据库连接的属性
PDO::getAvailableDrivers — 返回一个可用驱动的数组
PDO::inTransaction — 检查是否在一个事务内
PDO::lastInsertId — 返回最后插入行的ID或序列值
PDO::prepare — Prepares a statement for execution and returns a statement object
PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object
PDO::quote — Quotes a string for use in a query.
PDO::rollBack — 回滚一个事务
PDO::setAttribute — 设置属性
PDOStatement — PDOStatement 类
PDOStatement::bindColumn — 绑定一列到一个 PHP 变量
PDOStatement::bindParam — 绑定一个参数到指定的变量名
PDOStatement::bindValue — 把一个值绑定到一个参数
PDOStatement::closeCursor — 关闭游标 , 使语句能再次被执行 。
PDOStatement::columnCount — 返回结果集中的列数
PDOStatement::debugDumpParams — 打印一条 SQL 预处理命令
PDOStatement::errorCode — 获取跟上一次语句句柄操作相关的 SQLSTATE
PDOStatement::errorInfo — 获取跟上一次语句句柄操作相关的扩展错误信息
PDOStatement::execute — 执行一条预处理语句
PDOStatement::fetch — 从结果集中获取下一行
PDOStatement::fetchAll — 返回一个包含结果集中所有行的数组
PDOStatement::fetchColumn — 从结果集中的下一行返回单独的一列 。
PDOStatement::fetchObject — 获取下一行并作为一个对象返回 。
PDOStatement::getAttribute — 检索一个语句属性
PDOStatement::getColumnMeta — 返回结果集中一列的元数据
PDOStatement::nextRowset — 在一个多行集语句句柄中推进到下一个行集
PDOStatement::rowCount — 返回受上一个 SQL 语句影响的行数
PDOStatement::setAttribute — 设置一个语句属性
PDOStatement::setFetchMode — 为语句设置默认的获取模式 。
PDOException — PDOException 异常类
PDO 驱动
CUBRID— CUBRID Functions
MS SQL Server— Microsoft SQL Server and Sybase Functions
Firebird— Firebird Functions
IBM— IBM Functions
Informix— Informix Functions
MySQL— MySQL Functions
MS SQL Server— Microsoft SQL Server Functions
Oracle— Oracle Functions
ODBC and DB2— ODBC and DB2 Functions
PostgreSQL— PostgreSQL Functions
SQLite— SQLite Functions
4D— 4D Functions
<?php
Class SafePDO extends PDO {
public static function exception_handler {
// Output the exception details
die);
}
public function __construct) {
// Temporarily change the PHP exception handler while we . . .
set_exception_handler);
// . . . create a PDO object
parent::__construct;
// Change the exception handler back to whatever it was before
restore_exception_handler;
}
}
?>
Para usarla hay que crear un archivo PHP llamado por ejemplo SafePDO con el contenido del archivo citado m??s arriba.
Y en cuando tengamos que conectar a nuestra base de datos:<?php
include_once;
$dsn = \’mysql:host=\’.DB_HOST.\’;dbname=\’.DB_NAME.\’;charset=utf8\’;
$opt = array;
$pdo = new SafePDO;?>[3] Sbastien Gourmand [2013-07-08 10:19:25]
Merge the prepare and execute in one function like a sprintf.
And like sprintf, I choose to use unnamed args??
you could still use old insecure querywith renamed function ??
<?php
class MyPDO extends PDO{
const PARAM_host=\’localhost\’;
const PARAM_port=\’3306\’;
const PARAM_db_name=\’test\’;
const PARAM_user=\’root\’;
const PARAM_db_pass=\’\’;
public function __construct{
parent::__construct;
}
public function query{
//secured query with prepare and execute
$args = func_get_args;
array_shift;
//first element is not an argument but the query itself, should removed
$reponse = parent::prepare;
$reponse->execute;
return $reponse;
}
public function insecureQuery{
//you can use the old query at your risk ?? and should use secure quote function with it
return parent::query;
}
}
$db = new MyPDO;$db->setAttribute;
$t1 = isset?$_GET[\”t1\”]:1;
// need to be securised for injonction$t2 = isset?$_GET[\”t2\”]:2;
// need to be securised for injonction$t3 = isset?$_GET[\”t3\”]:3;
// need to be securised for injonction$ret = $db->query;
//$ret = $db->insecureQuery);
while )
{
echo $o->nom.PHP_EOL;
}
?>
[5] lkmorlan at uwaterloo dot ca [2010-06-29 09:38:33]
This works to get UTF8 data from MSSQL:<?php$db = new PDO;?>[7] paul dot maddox at gmail dot com [2009-08-27 05:54:14]
I decided to create a singleton wrapper for PDO that ensures only one instance is ever used.
It uses PHP 5.3.0\’s __callStatic functionality to pass on statically called methods to PDO.
This means you can just call it statically from anywhere without having to initiate or define the object.
Usage examples:<?php DB::exec;
foreach as $row){
print_r;
}
?>
Code:
<?php
class DB {
private static $objInstance;
private function __construct {}
private function __clone {}
public static function getInstance {
if{
self::$objInstance = new PDO;
self::$objInstance->setAttribute;
}
return self::$objInstance;
}end method }
?>
[9] cmcculloh [2008-06-25 12:14:44]
It appears that PDO SQL statements can not make use of comments. Or at least, when I was trying to use them with mine it was crashing without error and giving me a blank page .
[11] neonmandk at gmail dot com [2007-12-10 04:29:51]
If you will make a OBJ row from PDO you can use this eg.
$resKampange = $dbc->prepare;
$resKampange->execute;
$rowKampange = $resKampange->fetch;
echo $rowKampange->felt1;
Good lock :0)
[13] nospam dot list at unclassified dot de [2007-11-13 16:24:31]
When using persistent connections, pay attention not to leave the database connection in some kind of locked state. This can happen when you start a transaction by handmethod), possibly even acquire some locksand then your PHP script ends with a fatal error, unhandled exception or under other circumstances that lead to an unclean exit.
To use that database again, it may then be necessary to disable the persistence attribute to get a new database connection or restart the web server.It does not workto close a persistent database connection – it will not actually be closed but instead returned to PDO\’s connection pool.
The only thing you can do to resolve the lock as a regular useris to try and get all of your persistent connections in a single script and unlock the tables resp. end the transactions with the appropriate SQL statements . Should they fail, there is no problem, but one or some of them might succeed and thereby resolve your locking problem.
[15] Konstantin at Tokar dot ru [2007-10-16 08:34:21]
Example 5:
<?php
try { $dbh = new PDO);
…….
}
catch{
$dbh->rollBack;
echo \”Failed: \” . $e->getMessage;
}
?>
We must change the last two lines to catch the error connecting to the database:
} catch{
echo \”Failed: \” . $e->getMessage;
$dbh->rollBack;
}
?>
[17] metalim [2007-05-25 05:38:07]
From Oracle example:<?php$stmt->beginTransaction;$stmt->execute;$stmt->commit;?>PDOStatement has no beginTransaction, nor commit. Please fix documentation.
[19] djlopez at gmx dot de [2007-03-12 05:04:53]
Note this:
Won\’t work:
$sth = $dbh->prepare;THIS WORKS!
$sth = $dbh->prepare;Parameters cannot be applied on column names!!
[21] php at moechofe dot com [2007-02-17 11:52:59]Simple example to extends PDO
<?php
class connexion extends PDO{
public $query = null;
public function prepare )
{
$this->query = $statement;
return parent::prepare );
}
public function last_query
{
return $this->query;
}
}
class connexion_statement extends PDOStatement{
protected $pdo; protected function __construct
{
$this->pdo = $pdo;
}
// return first column of first row
public function fetchFirst
{
$row = $this->fetch;
return $row[0];
}
// real cast number
public function fetch
{
$row = parent::fetch;
if )
foreach
if) === $value )
$row[$key] = intval;
elseif) === $value )
$row[$key] = floatval; return $row;
}
// permit $prepare->execute;
public function execute
{
if )
return parent::execute; else
{
$args = func_get_args;
return eval;\’ );
}
} public function last_query
{
return $this->pdo->last_query;
}
}
$pdo = new connexion;
$pdo->setAttribute ) );
?>
[38291 ******you should try to leave the host= and port= parts out of the connection string. This sounds strange, but this is an \”option\” of Postgre. If you have not activated the TCP/IP port in postgresql.conf then postgresql doesn\’t accept any incoming requests from an TCP/IP port. If you use host= in your connection string you are going to connect to Postgre via TCP/IP, so that\’s not going to work. If you leave the host= part out of your connection string you connect to Postgre via the Unix domain sockets, which is faster and more secure, but you can\’t connect with the database via any other PC as the localhost.******Sincerely,Aouie[24] paulius_k at yahoo dot com [2006-07-25 08:42:58]If you need to get Output variable from MSSQL stored procedure, try this :– PROCEDURECREATE PROCEDURE spReturn_Int @err int OUTPUT ASSET @err = 11GO$sth = $dbh->prepare;
$sth->bindParam;
$sth->execute;
print \”procedure returned $return_value\\n\”;
[26] pokojny at radlight dot com [2006-04-23 08:50:58]
I wanted to extend PDO class to store statistics of DB usage, and I faced some problems. I wanted to count number of created statements and number of their executings. So PDOStatement should have link to PDO that created it and stores the statistical info. The problem was that I didn\’t knew how PDO creates PDOStatement , so I have created these two classes:<?php
class PDOp {
protected $PDO;
public $numExecutes;
public $numStatements;
public function __construct {
$this->PDO = new PDO;
$this->numExecutes = 0;
$this->numStatements = 0;
}
public function __call {
return call_user_func_array, $args);
}
public function prepare {
$this->numStatements++;
$args = func_get_args;
$PDOS = call_user_func_array, $args);
return new PDOpStatement;
} public function query {
$this->numExecutes++;
$this->numStatements++;
$args = func_get_args;
$PDOS = call_user_func_array, $args);
return new PDOpStatement;
}
public function exec {
$this->numExecutes++;
$args = func_get_args;
return call_user_func_array, $args);
}
} class PDOpStatement implements IteratorAggregate {
protected $PDOS;
protected $PDOp;
public function __construct {
$this->PDOp = $PDOp;
$this->PDOS = $PDOS;
}
public function __call {
return call_user_func_array, $args);
}
public function bindColumn {
if
$this->PDOS->bindColumn;
else
$this->PDOS->bindColumn;
}
public function bindParam {
if
$this->PDOS->bindParam;
else
$this->PDOS->bindParam;
}
public function execute {
$this->PDOp->numExecutes++;
$args = func_get_args;
return call_user_func_array, $args);
}
public function __get {
return $this->PDOS->$property;
}
public function getIterator {
return $this->PDOS;
}
}
?>
Classes have properties with original PDO and PDOStatement objects, which are providing the functionality to PDOp and PDOpStatement.
From outside, PDOp and PDOpStatement look like PDO and PDOStatement, but also are providing wanted info.
[28] www.navin.biz [2006-02-19 10:16:04]
Below is an example of extending PDO & PDOStatement classes:<?phpclass Database extends PDO{
function __construct
{
parent::__construct; $this->setAttribute));
}
}class DBStatement extends PDOStatement{
public $dbh; protected function __construct
{
$this->dbh = $dbh; $this->setFetchMode;
} public function foundRows
{
$rows = $this->dbh->prepare AS rows\’, array); $rows->execute; $rowsCount = $rows->fetch->rows; $rows->closeCursor; return $rowsCount;
}
}?>
[30] shaolin at adf dot nu [2006-02-07 18:18:50]
If your having problems re-compiling PHP with PDO as shared module try this.
–enable-pdo=shared
–with-pdo-mysql=shared,/usr/local/mysql
–with-sqlite=shared
–with-pdo-sqlite=shared
1. If PDO is built as a shared modules, all PDO drivers must also be
built as shared modules.
2. If ext/pdo_sqlite is built as a shared module, ext/sqlite must also
be built as a shared module.
3. In the extensions entries, if ext/pdo_sqlite is built as a shared
module, php.ini must specify pdo_sqlite first, followed by sqlite.
[32] Matthias Leuffen [2005-12-04 01:36:13]
Hi there,
because of ZDE 5.0 and other PHP-IDEs do not seem to support PDO from PHP5.1 in code-completion-database yet, I wrote a code-completion alias for the PDO class.
NOTE: This Class has no functionality and should be only included to your IDE-Project but NOT to your application.<?phpclass PDO {const ERR_ALREADY_EXISTS = 0;const ERR_CANT_MAP = 0;const ERR_NOT_FOUND = 0;const ERR_SYNTAX = 0;const ERR_CONSTRAINT = 0;const ERR_MISMATCH = 0;const ERR_DISCONNECTED = 0;const ERR_NONE = 0;const ATTR_ERRMODE = 0;const ATTR_TIMEOUT = 0;const ATTR_AUTOCOMMIT = 0;const ATTR_PERSISTENT = 0;// Values for ATTR_ERRMODEconst ERRMODE_EXCEPTION = 0;const ERRMODE_WARNING = 0;const FETCH_ASSOC = 0;const FETCH_NUM = 0;const FETCH_OBJ = 0;public function __construct {}public function prepare{}public function query{}public function quote{}public function exec{}public function lastInsertId {}public function beginTransaction{}public function commit{}public function rollBack{}public function errorCode{}public function errorInfo{}
}class PDOStatement {public function bindValue{}public function fetch{}public function nextRowset{}public function execute {}public function errorCode{}public function errorInfo{}public function rowCount{}public function setFetchMode{}public function columnCount{}
}
[#33] ng4rrjanbiah at rediffmail dot com [2005-03-15 22:53:49]Some useful links on PDO:1. PDO Wiki 2. Introducing PHP Data Objects , [226 KB], Wez Furlong, 2004-09-243. The PHP 5 Data ObjectAbstraction Layer and Oracle , [60.85 KB], Wez Furlong, 2004-07-284. PDO – Why it should not be part of core PHP! , Critical review, [38.63 KB], Alan Knowles, 2004-10-22
相关推荐:
PHP使用pdo连接access数据库并循环显示数据操作
【php的PDO操作】以上就是朝夕生活(www.30zx.com)关于“php的PDO操作”的详细内容,希望对大家有所帮助!
猜你喜欢
- 头条创作,原创和首发的区别是什么?
- win764位系统中如何打开nrg文件的问题
- 世界十大香料品牌排行榜:奇华顿第2,第5美国最大香料品牌
- 关于苹果数据线的秘密–你的数据线还好吗?
- 去,你的苹果数据线到底是有多“娇贵”
- 没赶上火车,他退票不成把票撕了,结果“悲剧”了…
- 凉皮品牌排行榜前10:勾魂凉皮第一,源自北京知名品牌
- [微揭示] 这件事,其实可以通过“改签”来解决!
- 让您的春运回家路体验更美好
