|
PDO FunctionsThe PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server. PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. PDO does not provide a database abstraction; it doesn't rewrite SQL or emulate missing features. You should use a full-blown abstraction layer if you need that facility. PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP. Procedure 2. PHP 5.1 and up on Unix systems
Procedure 3. PHP 5.0.0 and up on Unix systems
Procedure 4. Windows users running PHP 5.1.0 and up
The behaviour of these functions is affected by settings in
Here's a short explanation of the configuration directives.
The following drivers currently implement the PDO interface:
Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any). Example 1737. Connecting to MySQL<?php
If there are any connection errors, a Example 1738. Handling connection errors<?php
Warning:
If your application does not catch the exception thrown from the PDO
constructor, the default action taken by the zend engine is to terminate
the script and display a back trace. This back trace will likely reveal
the full database connection details, including the username and
password. It is your responsibility to catch this exception, either
explicitly (via a
Upon successful connection to the database, an instance of the PDO class
is returned to your script. The connection remains active for the
lifetime of that PDO object. To close the connection, you need to
destroy the object by ensuring that all remaining references to it are
deleted--you do this by assigning Example 1739. Closing a connection<?php Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application. Example 1740. Persistent connections<?php
Note:
If you wish to use persistent connections, you must set
Note:
If you're using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it's recommended that you don't use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules. Now that you're connected via PDO, you must understand how PDO manages transactions before you start issuing queries. If you've never encountered transactions before, they offer 4 major features: Atomicity, Consistency, Isolation and Durability (ACID). In layman's terms, any work carried out in a transaction, even if it is carried out in stages, is guaranteed to be applied to the database safely, and without interference from other connections, when it is committed. Transactional work can also be automatically undone at your request (provided you haven't already committed it), which makes error handling in your scripts easier. Transactions are typically implemented by "saving-up" your batch of changes to be applied all at once; this has the nice side effect of drastically improving the efficiency of those updates. In other words, transactions can make your scripts faster and potentially more robust (you still need to use them correctly to reap that benefit). Unfortunately, not every database supports transactions, so PDO needs to run in what is known as "auto-commit" mode when you first open the connection. Auto-commit mode means that every query that you run has its own implicit transaction, if the database supports it, or no transaction if the database doesn't support transactions. If you need a transaction, you must use the PDO->beginTransaction() method to initiate one. If the underlying driver does not support transactions, a PDOException will be thrown (regardless of your error handling settings: this is always a serious error condition). Once you are in a transaction, you may use PDO->commit() or PDO->rollBack() to finish it, depending on the success of the code you run during the transaction. When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back. This is a safety measure to help avoid inconsistency in the cases where the script terminates unexpectedly--if you didn't explicitly commit the transaction, then it is assumed that something went awry, so the rollback is performed for the safety of your data.
Warning:
The automatic rollback only happens if you initiate the transaction via PDO->beginTransaction(). If you manually issue a query that begins a transaction PDO has no way of knowing about it and thus cannot roll it back if something bad happens. Example 1741. Executing a batch in a transactionIn the following sample, let's assume that we are creating a set of entries for a new employee, who has been assigned an ID number of 23. In addition to entering the basic data for that person, we also need to record their salary. It's pretty simple to make two separate updates, but by enclosing them within the PDO->beginTransaction() and PDO->commit() calls, we are guaranteeing that no one else will be able to see those changes until they are complete. If something goes wrong, the catch block rolls back all changes made since the transaction was started, and then prints out an error message. <?php You're not limited to making updates in a transaction; you can also issue complex queries to extract data, and possibly use that information to build up more updates and queries; while the transaction is active, you are guaranteed that no one else can make changes while you are in the middle of your work. In truth, this isn't 100% correct, but it is a good-enough introduction, if you've never heard of transactions before. Many of the more mature databases support the concept of prepared statements. What are they? You can think of them as a kind of compiled template for the SQL that you want to run, that can be customized using variable parameters. Prepared statements offer two major benefits:
Prepared statements are so useful that they are the only feature that PDO will emulate for drivers that don't support them. This ensures that you will be able to use the same data access paradigm regardless of the capabilities of the database. Example 1742. Repeated inserts using prepared statements
This example performs an INSERT query by substituting a <?php Example 1743. Repeated inserts using prepared statements
This example performs an INSERT query by substituting a <?php Example 1744. Fetching data using prepared statementsThis 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 If the database driver supports it, you may also bind parameters for output as well as input. Output parameters are typically used to retrieve values from stored procedures. Output parameters are slightly more complex to use than input parameters, in that you must know how large a given parameter might be when you bind it. If the value turns out to be larger than the size you suggested, an error is raised. Example 1745. Calling a stored procedure with an output parameter<?php You may also specify parameters that hold values both input and output; the syntax is similar to output parameters. In this next example, the string 'hello' is passed into the stored procedure, and when it returns, hello is replaced with the return value of the procedure. Example 1746. Calling a stored procedure with an input/output parameter<?php Example 1747. Invalid use of placeholder<?php PDO offers you a choice of 3 different error handling strategies, to fit your style of application development.
PDO standardizes on using SQL-92 SQLSTATE error code strings; individual PDO drivers are responsible for mapping their native codes to the appropriate SQLSTATE codes. The PDO->errorCode() method returns a single SQLSTATE code. If you need more specific information about an error, PDO also offers an PDO->errorInfo() method which returns an array containing the SQLSTATE code, the driver specific error code and driver specific error string.
At some point in your application, you might find that you need to store
"large" data in your database. Large typically means "around 4kb or
more", although some databases can happily handle up to 32kb before data becomes
"large". Large objects can be either textual or binary in nature. PDO
allows you to work with this large data type by using the
Example 1748. Displaying an image from a databaseThis 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 Example 1749. Inserting an image into a databaseThis 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 Example 1750. Inserting an image into a database: OracleOracle 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 Represents a connection between PHP and a database server.
Represents a prepared statement and, after the statement is executed, an associated result set.
Represents an error raised by PDO. You should not throw a
Example 1751. The PDOException class<?php The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Warning:
PDO uses class constants since PHP 5.1. Prior releases use global constants
in the form
Table of Contents
Code Examples / Notes » ref.pdotomasz dot wasiluk
Watch out for putting spaces in the DSN mysql:host=localhost;dbname=test works mysql: host = localhost; dbname=test works mysql: host = localhost; dbname = test doesn't work... ng4rrjanbiah
Some useful links on PDO: 1. PDO Wiki ( http://wiki.cc/php/PDO ) 2. Introducing PHP Data Objects ( http://netevil.org/downloads/Introducing-PDO.ppt ), [226 KB], Wez Furlong, 2004-09-24 3. The PHP 5 Data Object (PDO) Abstraction Layer and Oracle ( http://www.oracle.com/technology/pub/articles/php_experts/otn_pdo_oracle5.html ), [60.85 KB], Wez Furlong, 2004-07-28 4. PDO - Why it should not be part of core PHP! ( http://www.akbkhome.com/blog.php/View/55/ ), Critical review, [38.63 KB], Alan Knowles, 2004-10-22 HTH, R. Rajesh Jeba Anbiah php
Simple example to extends PDO <?php class connexion extends PDO { public $query = null; public function prepare( $statement, $driver_options = array() ) { $this->query = $statement; return parent::prepare( $statement, $driver_options = array() ); } public function last_query() { return $this->query; } } class connexion_statement extends PDOStatement { protected $pdo; protected function __construct($pdo) { $this->pdo = $pdo; } // return first column of first row public function fetchFirst() { $row = $this->fetch( PDO::FETCH_NUM ); return $row[0]; } // real cast number public function fetch( $fetch_style = null, $cursor_orientation = null, $cursor_offset = null ) { $row = parent::fetch( $fetch_style, $cursor_orientation, $cursor_offset ); if( is_array($row) ) foreach( $row as $key => $value ) if( strval(intval($value)) === $value ) $row[$key] = intval($value); elseif( strval(floatval($value)) === $value ) $row[$key] = floatval($value); return $row; } // permit $prepare->execute( $arg1, $arg2, ... ); public function execute( $args = null ) { if( is_array( $args ) ) return parent::execute( $args ); else { $args = func_get_args(); return eval( 'return parent::execute( $args );' ); } } public function last_query() { return $this->pdo->last_query(); } } $pdo = new connexion( ... ); $pdo->setAttribute( PDO::ATTR_STATEMENT_CLASS, array( 'connexion_statement', array($pdo) ) ); ?> djlopez
Please note this: Won't work: $sth = $dbh->prepare('SELECT name, colour, calories FROM ? WHERE calories < ?'); THIS WORKS! $sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ?'); The parameter cannot be applied on table names!! keyvez
PDO doesn't return OUTPUT params from mssql stored procedures /* Stored Procedure Create Code: */ /* CREATE PROCEDURE p_sel_all_termlength @err INT OUTPUT AS SET @err = 2627 */ /* PHP Code: */ <?php $Link = new PDO('mssql:host=sqlserver;dbname=database', 'username', 'password'); $ErrorCode = 0; $Stmt = $Link->prepare('p_sel_all_termlength ?'); $Stmt->bindParam(1,$ErrorCode,PDO::PARAM_INT,4); $Stmt->execute(); echo "Error = " . $ErrorCode . "\n"; ?> /* PHP Output: Error = 0 */ webograph
pdo doesn't care about charsets. if you want to have your connection in unicode / utf-8 or any other encoding, you'll have to tell your database, for example using $dbh->exec('SET CHARACTER SET utf8') (mysql).
djlopez
Note this: Won't work: $sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE ? < ?'); THIS WORKS! $sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ?'); Parameters cannot be applied on column names!! anton dot clarke
Not all PDO drivers return a LOB as a file stream; mysql 5 is one example. Therefore when streaming a mime typed object from the database you cannot use fpassthru. The following is a modified example that works with a mysql database. (Tested FreeBSD v 6.2 with mysql 5.0.45 and php 5.2.3) <?php ob_start(); $db = new PDO('mysql:host=localhost;dbname=<SOMEDB>', '<USERNAME>', 'PASSWORD'); $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); ob_clean(); header("Content-Type: $type"); echo $lob; // fpassthru reports an error that $lob is not a stream so echo is used in place. ob_end_flush(); ?> Please note the inclusion of buffer control. I only needed this when using 'include','include_once','require', or 'require_once' - my feeling is there is a subtle issue with those options as even an empty include file caused a buffer issue for me. === AND YES, I DID CHECK MY INCLUDE FILES DID NOT HAVE SPURIOUS WHITESPACE ETC OUTSIDE THE <?php ?> DELIMITERS! === tim dot boonstra
Missing info from this page: PDO::ATTR_ORACLE_NULLS (available with all drivers, not just Oracle): Conversion of NULL and empty strings. PDO::NULL_NATURAL (integer): No conversion. PDO::NULL_EMPTY_STRING (integer): Empty string is converted to NULL. PDO::NULL_TO_STRING (integer): NULL is converted to an empty string. $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_TO_STRING); bart
It seems MySQL doesn't support scrollable cursors. So unfortunately PDO::CURSOR_SCROLL wont work.
katzke
It doesn't seem at this time that there's a practical solution (besides creating multiple PDO objects and therefore DB connections) to accessing and switching between multiple databases -- as with the mysql_select_db function.
shaolin
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. webform
If you use $dbh = new PDO('pgsql:host=localhost;dbname=test_basic01', $user, $pass); and you get the following error: PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[08006] [7] could not connect to server: Connection refused\n\tIs the server running on host "localhost" and accepting\n\tTCP/IP connections on port 5432?' then as pointed out under pg_connect at: http://www.php.net/manual/en/function.pg-connect.php#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 paulius_k
If you need to get Output variable from MSSQL stored procedure, try this : -- PROCEDURE CREATE PROCEDURE spReturn_Int @err int OUTPUT AS SET @err = 11 GO $sth = $dbh->prepare("EXECUTE spReturn_Int ?"); $sth->bindParam(1, $return_value, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT); $sth->execute(); print "procedure returned $return_value\n"; smileaf
If you intend on extending PDOStatement and your using setAttribute(PDO::ATTR_STATEMENT_CLASS, ...) you must override the __construct() of your PDOStatement class. failure to do so will result in an error on any PDO::query() call. Warning: PDO::query() [function.PDO-query]: SQLSTATE[HY000]: General error: user-supplied statement does not accept constructor arguments Here is a minimum PDO and PDOStatement class <?php class Database extends PDO { function __construct($dsn, $username="", $password="", $driver_options=array()) { parent::__construct($dsn,$username,$password, $driver_options); $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array($this))); } } class DBStatement extends PDOStatement { public $dbh; protected function __construct($dbh) { $this->dbh = $dbh; } } ?> pokojny
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 (constructor parameters and so on), so I have created these two classes: <?php /** * PHP Document Object plus * * PHP Document Object plus is library with functionality of PDO, entirely written * in PHP, so that developer can easily extend it's classes with specific functionality, * such as providing database usage statistics implemented in v1.0b * * @author Peter Pokojny * @license http://opensource.org/licenses/gpl-license.php GNU Public License */ class PDOp { protected $PDO; public $numExecutes; public $numStatements; public function __construct($dsn, $user=NULL, $pass=NULL, $driver_options=NULL) { $this->PDO = new PDO($dsn, $user, $pass, $driver_options); $this->numExecutes = 0; $this->numStatements = 0; } public function __call($func, $args) { return call_user_func_array(array(&$this->PDO, $func), $args); } public function prepare() { $this->numStatements++; $args = func_get_args(); $PDOS = call_user_func_array(array(&$this->PDO, 'prepare'), $args); return new PDOpStatement($this, $PDOS); } public function query() { $this->numExecutes++; $this->numStatements++; $args = func_get_args(); $PDOS = call_user_func_array(array(&$this->PDO, 'query'), $args); return new PDOpStatement($this, $PDOS); } public function exec() { $this->numExecutes++; $args = func_get_args(); return call_user_func_array(array(&$this->PDO, 'exec'), $args); } } class PDOpStatement implements IteratorAggregate { protected $PDOS; protected $PDOp; public function __construct($PDOp, $PDOS) { $this->PDOp = $PDOp; $this->PDOS = $PDOS; } public function __call($func, $args) { return call_user_func_array(array(&$this->PDOS, $func), $args); } public function bindColumn($column, &$param, $type=NULL) { if ($type === NULL) $this->PDOS->bindColumn($column, $param); else $this->PDOS->bindColumn($column, $param, $type); } public function bindParam($column, &$param, $type=NULL) { if ($type === NULL) $this->PDOS->bindParam($column, $param); else $this->PDOS->bindParam($column, $param, $type); } public function execute() { $this->PDOp->numExecutes++; $args = func_get_args(); return call_user_func_array(array(&$this->PDOS, 'execute'), $args); } public function __get($property) { 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. nicolas
I use PDO with the ODBC driver to query stored procedures in a MS SQL Server 2005 Database under Windows XP Professional with IIS 5 and PHP 5.1.4. You may have the same problems with a different configuration. I experienced 2 very time consuming errors: 1. The first one is when you return the result of a SELECT query, and you get the following clueless message: >>> Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[24000]: Invalid cursor state: 0 [Microsoft][SQL Native Client]Invalid cursor state (SQLFetchScroll[0] at ext\pdo_odbc\odbc_stmt.c:372)' in (YOUR_TRACE_HERE) <<< Your exact message may be different, the part to pay attention to is "Invalid cursor state". -> I found that I had this error because I didn't include "SET NOCOUNT ON" in the *body* of the stored procedure. By default the server returns a special piece of information along with the results, indicating how many rows were affected by the stored procedure, and that's not handled by PDO. 2. The second error I had was: >>> Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[22003]: Numeric value out of range: 0 [Microsoft][SQL Native Client]Numeric value out of range (SQLFetchScroll[0] at ext\pdo_odbc\odbc_stmt.c:372)' in (YOUR_TRACE_HERE) <<< Another meaningless error "Numeric value out of range"... -> I was actually returning a date datatype (datetime or smalldatetime) "as is", that is, without converting it to varchar before including it in the result set... I don't know if PDO is responsible for converting it to a PHP datatype, but it doesn't. Convert it before it reaches PHP. chad 0x40 herballure 0x2e com
I just discovered that PDOStatement implements Traversable. That means you can use it in foreach loops to iterate over rows: <?php $pdo = new PDO('mysql:dbname=test'); $sth = $pdo->query('SELECT data FROM t1'); foreach($sth as $row) { echo $row['data'], "\n"; } ?> xorinox
I have seen a lot of user struggling with calling mysql procedures with in/out/inout parameters using bindParam. There seems to be a bug or missing feature within the mysql C api. This at least I could find out after reading a lot of posts at different places... At the moment I workaround it like below. $con is a PDO object: <?php //in $proc = $con->prepare( "call proc_in( @i_param )" ); $con->query( "set @i_param = 'myValue'" ); $proc->execute(); //out $proc = $con->prepare( "call proc_out( @o_param )" ); $proc->execute(); $o_param = $con->query( "select @o_param" )->fetchColumn(); //inout $proc = $con->prepare( "call proc_inout( @io_param )" ); $con->query( "set @io_param = 'myValue'" ); $proc->execute(); $io_param = $con->query( "select @io_param" )->fetchColumn(); ?> dariusz kielar
I found a nice pdo modification written in php called Open Power Driver. It has identical API with the original, but allows you to cache query results: http://www.openpb.net/opd.php
matthias leuffen
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. <?php /** * This is a Code-Completion only file * (For use with ZDE or other IDEs) * * Do NOT include() or require() this to your code * * @author Matthias Leuffen */ class PDO { /** * Error Constants * */ 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; /** * Attributes (to use in PDO::setAttribute() as 1st Parameter) * */ const ATTR_ERRMODE = 0; const ATTR_TIMEOUT = 0; const ATTR_AUTOCOMMIT = 0; const ATTR_PERSISTENT = 0; // Values for ATTR_ERRMODE const ERRMODE_EXCEPTION = 0; const ERRMODE_WARNING = 0; const FETCH_ASSOC = 0; const FETCH_NUM = 0; const FETCH_OBJ = 0; public function __construct($uri, $user, $pass, $optsArr) { } /** * Prepare Statement: Returns PDOStatement * * @param string $prepareString * @return PDOStatement */ public function prepare ($prepareString) { } public function query ($queryString) { } public function quote ($input) { } public function exec ($statement) { } public function lastInsertId() { } public function beginTransaction () { } public function commit () { } public function rollBack () { } public function errorCode () { } public function errorInfo () { } } class PDOStatement { public function bindValue ($no, $value) { } public function fetch () { } public function nextRowset () { } public function execute() { } public function errorCode () { } public function errorInfo () { } public function rowCount () { } public function setFetchMode ($mode) { } public function columnCount () { } } metalim
From Oracle example: <? $stmt->beginTransaction(); $stmt->execute(); $stmt->commit(); ?> PDOStatement has no beginTransaction(), nor commit(). Please fix documentation. konstantin
Example 5: <?php try { $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2', array(PDO::ATTR_PERSISTENT => true)); ....... } catch (Exception $e) { $dbh->rollBack(); echo "Failed: " . $e->getMessage(); } ?> We must change the last two lines to catch the error connecting to the database: } catch (Exception $e) { echo "Failed: " . $e->getMessage(); $dbh->rollBack(); } ?> www.navin.biz
Below is an example of extending PDO & PDOStatement classes: <?php class Database extends PDO { function __construct() { parent::__construct('mysql:dbname=test;host=localhost', 'root', ''); $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array($this))); } } class DBStatement extends PDOStatement { public $dbh; protected function __construct($dbh) { $this->dbh = $dbh; $this->setFetchMode(PDO::FETCH_OBJ); } public function foundRows() { $rows = $this->dbh->prepare('SELECT found_rows() AS rows', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE)); $rows->execute(); $rowsCount = $rows->fetch(PDO::FETCH_OBJ)->rows; $rows->closeCursor(); return $rowsCount; } } ?> |
Change Language.NET Functions Apache-specific Functions Alternative PHP Cache Advanced PHP debugger Array Functions Aspell functions [deprecated] BBCode Functions BCMath Arbitrary Precision Mathematics Functions PHP bytecode Compiler Bzip2 Compression Functions Calendar Functions CCVS API Functions [deprecated] Class/Object Functions Classkit Functions ClibPDF Functions [deprecated] COM and .Net (Windows) Crack Functions Character Type Functions CURL Cybercash Payment Functions Credit Mutuel CyberMUT functions Cyrus IMAP administration Functions Date and Time Functions DB++ Functions Database (dbm-style) Abstraction Layer Functions dBase Functions DBM Functions [deprecated] dbx Functions Direct IO Functions Directory Functions DOM Functions DOM XML Functions enchant Functions Error Handling and Logging Functions Exif Functions Expect Functions File Alteration Monitor Functions Forms Data Format Functions Fileinfo Functions filePro Functions Filesystem Functions Filter Functions Firebird/InterBase Functions Firebird/Interbase Functions (PDO_FIREBIRD) FriBiDi Functions FrontBase Functions FTP Functions Function Handling Functions GeoIP Functions Gettext Functions GMP Functions gnupg Functions Net_Gopher Haru PDF Functions hash Functions HTTP Hyperwave Functions Hyperwave API Functions i18n Functions IBM Functions (PDO_IBM) IBM DB2 iconv Functions ID3 Functions IIS Administration Functions Image Functions Imagick Image Library IMAP Informix Functions Informix Functions (PDO_INFORMIX) Ingres II Functions IRC Gateway Functions PHP / Java Integration JSON Functions KADM5 LDAP Functions libxml Functions Lotus Notes Functions LZF Functions Mail Functions Mailparse Functions Mathematical Functions MaxDB PHP Extension MCAL Functions Mcrypt Encryption Functions MCVE (Monetra) Payment Functions Memcache Functions Mhash Functions Mimetype Functions Ming functions for Flash Miscellaneous Functions mnoGoSearch Functions Microsoft SQL Server Functions Microsoft SQL Server and Sybase Functions (PDO_DBLIB) Mohawk Software Session Handler Functions mSQL Functions Multibyte String Functions muscat Functions MySQL Functions MySQL Functions (PDO_MYSQL) MySQL Improved Extension Ncurses Terminal Screen Control Functions Network Functions Newt Functions NSAPI-specific Functions Object Aggregation/Composition Functions Object property and method call overloading Oracle Functions ODBC Functions (Unified) ODBC and DB2 Functions (PDO_ODBC) oggvorbis OpenAL Audio Bindings OpenSSL Functions Oracle Functions [deprecated] Oracle Functions (PDO_OCI) Output Control Functions Ovrimos SQL Functions Paradox File Access Parsekit Functions Process Control Functions Regular Expression Functions (Perl-Compatible) PDF Functions PDO Functions Phar archive stream and classes PHP Options&Information POSIX Functions Regular Expression Functions (POSIX Extended) PostgreSQL Functions PostgreSQL Functions (PDO_PGSQL) Printer Functions Program Execution Functions PostScript document creation Pspell Functions qtdom Functions Radius Rar Functions GNU Readline GNU Recode Functions RPM Header Reading Functions runkit Functions SAM - Simple Asynchronous Messaging Satellite CORBA client extension [deprecated] SCA Functions SDO Functions SDO XML Data Access Service Functions SDO Relational Data Access Service Functions Semaphore SESAM Database Functions PostgreSQL Session Save Handler Session Handling Functions Shared Memory Functions SimpleXML functions SNMP Functions SOAP Functions Socket Functions Standard PHP Library (SPL) Functions SQLite Functions SQLite Functions (PDO_SQLITE) Secure Shell2 Functions Statistics Functions Stream Functions String Functions Subversion Functions Shockwave Flash Functions Swish Functions Sybase Functions TCP Wrappers Functions Tidy Functions Tokenizer Functions Unicode Functions URL Functions Variable Handling Functions Verisign Payflow Pro Functions vpopmail Functions W32api Functions WDDX Functions win32ps Functions win32service Functions xattr Functions xdiff Functions XML Parser Functions XML-RPC Functions XMLReader functions XMLWriter Functions XSL functions XSLT Functions YAZ Functions YP/NIS Functions Zip File Functions Zlib Compression Functions |