CVI. PDO Functions


The 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.


PHP 5.1 and up on Unix systems

  1. If you're running a PHP 5.1 release, PDO is included in the distribution; it will be automatically enabled when you run configure. It is recommended that you build PDO as a shared extension, as this will allow you to take advantage of updates that are made available via PECL. The recommended configure line for building PHP with PDO support should enable zlib support (for the pear installer) as well. You may also need to enable the PDO driver for your database of choice; consult the documentation for database-specific PDO drivers to find out more about that.
    ./configure --with-zlib --enable-pdo=shared

  2. After installing PDO as a shared module, you must edit your php.ini file so that the PDO extension will be loaded automatically when PHP runs. You will also need to enable any database specific drivers there too; make sure that they are listed after the line, as PDO must be initialized before the database specific extensions can be loaded. If you built the extensions statically, you can skip this step.

  3. Having PDO as a shared module will allow you to run pear upgrade pdo as new versions of PDO are published, without forcing you to rebuild the whole of PHP. Note that if you do this, you also need to upgrade your database specific PDO drivers at the same time.

PHP 5.0 and up on Unix systems

  1. PDO is available as a PECL extension from Installation can be performed via the pear tool; this is enabled by default when you configure PHP. You should ensure that PHP was configured --with-zlib in order for pear to be able to handle the compressed package files.

  2. Run the following command to download, build, and install the latest stable version of PDO:
    pear install pdo

  3. If PDO is still in beta (and at the time of writing, it is), you will need to tell the pear tool that it's ok to fetch the beta package. Instead of running the command above, run the following:
    pear install pdo-beta

  4. The pear command automatically installs the PDO module into your PHP extensions directory. To enable the PDO extension on Linux or Unix operating systems, you must add the following line to php.ini:

    For more information about building PECL packages, consult the PECL installation section of the manual.

Windows users running PHP 5.1 and up

  1. PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file:

  2. Next, choose the other DB specific DLL files and either use dl() to load them at runtime, or enable them in php.ini below php_pdo.dll. For example:

    These DLLs should exist in the system's extension_dir.


这些函数的行为受 php.ini 的影响。

表格 1. PDO Configuration Options

pdo.dsn.* php.ini only 
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G


pdo.dsn.* string

Defines DSN alias. See PDO::__construct for thorough explanation.

PDO Drivers

The following drivers currently implement the PDO interface:

Driver nameSupported databases
PDO_DBLIBFreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRDFirebird/Interbase 6
PDO_OCIOracle Call Interface
PDO_ODBCODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_SQLITESQLite 3 and SQLite 2

Connections and Connection management

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).

例子 1. Connecting to mysql

= new PDO('mysql:host=localhost;dbname=test', $user, $pass);

If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().

例子 2. Handling connection errors

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
   foreach (
$dbh->query('SELECT * from FOO') as $row) {
$dbh = null;
catch (PDOException $e) {
"Error!: " . $e->getMessage() . "<br/>";

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 NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

例子 3. Closing a connection

= new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here

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

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.

例子 4. Persistent connections

= new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(

注: 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.

Transactions and auto-commit

Now that you're connected via PDO, you should to 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.


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.

例子 5. Executing a batch in a transaction

In 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.

$dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',

$dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
$dbh->exec("insert into salarychange (id, amount, changedate)
      values (23, 50000, NOW())"
catch (Exception $e) {
"Failed: " . $e->getMessage();

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.

Prepared statements and stored procedures

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:

  • The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize it's plan for executing the query. For complex queries this process can take up enough time that it will noticably slow down your application if you need to repeat the same query many times with different parameters. By using a prepared statement you avoid repeating the analyze/compile/optimize cycle. In short, prepared statements use fewer resources and thus run faster.

  • The parameters to prepared statements don't need to be quoted; the driver handles it for you. If your application exclusively uses prepared statements, you can be sure that no SQL injection will occur. (However, if you're still building up other parts of the query based on untrusted input, you're still at risk).

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.

例子 6. Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the named placeholders.

= $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;

// insert another row with different values
$name = 'two';
$value = 2;

例子 7. Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the positional ? placeholders.

= $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// insert one row
$name = 'one';
$value = 1;

// insert another row with different values
$name = 'two';
$value = 2;

例子 8. 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.

= $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if (
$stmt->execute(array($_GET['name']))) {
  while (
$row = $stmt->fetch()) {

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.

例子 9. Calling a stored procedure with an output parameter

= $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO_PARAM_STR, 4000);

// call the stored procedure

"procedure returned $return_value\n";

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.

例子 10. Calling a stored procedure with an input/output parameter

= $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

"procedure returned $value\n";

Errors and error handling

PDO offers you a choice of 3 different error handling strategies, to fit your style of application development.


    This is the default mode. PDO will simply set the error code for you to inspect using the PDO::errorCode() and PDO::errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement::errorCode() or PDOStatement::errorInfo() method on that object. If the error resulted from a call on the database object, you would invoke those methods on the database object instead.


    In addition to setting the error code, PDO will emit a traditional E_WARNING message. This setting is useful during debugging/testing, if you just want to see what problems occurred without interrupting the flow of the application.


    In addition to setting the error code, PDO will throw a PDOException and set its properties to reflect the error code and error information. This setting is also useful during debugging, as it will effectively "blow up" the script at the point of the error, very quickly pointing a finger at potential problem areas in your code (remember: transactions are automatically rolled back if the exception causes the script to terminate).

    Exception mode is also useful because you can structure your error handling more clearly than with traditional PHP-style warnings, and with less code/nesting than by running in silent mode and explicitly checking the return value of each database call.

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.

Large Objects (LOBs)

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 PDO_PARAM_LOB type code in your PDOStatement::bindParam() or PDOStatement::bindColumn() calls. PDO_PARAM_LOB tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.

例子 11. 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.

= new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->bindColumn(1, $type, PDO_PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO_PARAM_LOB);

header("Content-Type: $type");

例子 12. 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.

= 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);




Represents a connection between PHP and a database server.


  • PDO - constructs a new PDO object


  • beginTransaction - begins a transaction

  • commit - commits a transaction

  • errorCode - retrieves an error code, if any, from the database

  • errorInfo - retrieves an array of error information, if any, from the database

  • exec - issues an SQL statement and returns the number of affected rows

  • getAttribute - retrieves a database connection attribute

  • lastInsertId - retrieves the value of the last row that was inserted into a table

  • prepare - prepares an SQL statement for execution

  • query - issues an SQL statement and returns a result set

  • quote - returns a quoted version of a string for use in SQL statements

  • rollBack - roll back a transaction

  • setAttribute - sets a database connection attribute


Represents a prepared statement and, after the statement is executed, an associated result set.


  • bindColumn - binds a PHP variable to an output column in a result set

  • bindParam - binds a PHP variable to a parameter in the prepared statement

  • bindValue - binds a value to a parameter in the prepared statement

  • closeCursor - closes the cursor, allowing the statement to be executed again

  • columnCount - returns the number of columns in the result set

  • errorCode - retrieves an error code, if any, from the statement

  • errorInfo - retrieves an array of error information, if any, from the statement

  • execute - executes a prepared statement

  • fetch - fetches a row from a result set

  • fetchAll - fetches an array containing all of the rows from a result set

  • fetchColumn - returns the data from a single column in a result set

  • getAttribute - retrieves a PDOStatement attribute

  • getColumnMeta - retrieves metadata for a column in the result set

  • nextRowset - retrieves the next rowset (result set)

  • rowCount - returns the number of rows that were affected by the execution of an SQL statement

  • setAttribute - sets a PDOStatement attribute

  • setFetchMode - sets the fetch mode for a PDOStatement


以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

PDO_PARAM_BOOL (integer)

Represents a boolean data type.

PDO_PARAM_NULL (integer)

Represents the SQL NULL data type.

PDO_PARAM_INT (integer)

Represents the SQL INTEGER data type.

PDO_PARAM_STR (integer)

Represents the SQL CHAR, VARCHAR, or other string data type.

PDO_PARAM_LOB (integer)

Represents the SQL large object data type.

PDO_PARAM_STMT (integer)


Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO_PARAM_* data type.

PDO_FETCH_LAZY (integer)

Specifies that the fetch method shall return each row as an object with variable names that correspond to the column names returned in the result set. PDO_FETCH_LAZY creates the object variable names as they are accessed.


Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO_FETCH_ASSOC returns only a single value per column name.


Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO_FETCH_NAMED returns an array of values per column name.

PDO_FETCH_NUM (integer)

Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0.

PDO_FETCH_BOTH (integer)

Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.

PDO_FETCH_OBJ (integer)

Specifies that the fetch method shall return each row as an object with property names that correspond to the column names returned in the result set.


Specifies that the fetch method shall return TRUE and assign the values of the columns in the result set to the PHP variables to which they were bound with the PDOStatement::bindParam() or PDOStatement::bindColumn() methods.


Specifies that the fetch method shall return only a single requested column from the next row in the result set.


Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class.

PDO_FETCH_INTO (integer)

Specifies that the fetch method shall update an existing instance of the requested class, mapping the columns to named properties in the class.

PDO_FETCH_FUNC (integer)





If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.


Setting the prefetch size allows you to balance speed against memory usage for your application. Not all database/driver combinations support setting of the prefetch size.


Sets the timeout value in seconds for communications with the database.






PDO_ATTR_CASE (integer)

Force column names to a specific case specified by the PDO_CASE_* constants.




Returns the name of the driver.


Convert empty strings to SQL NULL values.


Request a persistent connection, rather than creating a new connection.


Prepend the containing catalog name to each column name returned in the result set. The catalog name and column name are separated by a decimal (.) character.


Prepend the containing table name to each column name returned in the result set. The table name and column name are separated by a decimal (.) character.


Do not raise an error or exception if an error occurs. The developer is expected to explicitly check for errors. This is the default mode.


Issue a PHP E_WARNING message if an error occurs.


Throw a PDOException if an error occurs.


Leave column names as returned by the database driver.

PDO_CASE_LOWER (integer)

Force column names to lower case.

PDO_CASE_UPPER (integer)

Force column names to upper case.


Fetch the next row in the result set. Valid only for scrollable cursors.


Fetch the previous row in the result set. Valid only for scrollable cursors.


Fetch the first row in the result set. Valid only for scrollable cursors.


Fetch the last row in the result set. Valid only for scrollable cursors.


Fetch the requested row by row number from the result set. Valid only for scrollable cursors.


Fetch the requested row by relative position from the current position of the cursor in the result set. Valid only for scrollable cursors.


Create a PDOStatement object with a forward-only cursor. This may improve the performance of your application but restricts your PDOStatement object to fetching one row at a time from the result set in a forward direction.


Create a PDOStatement object with a scrollable cursor. Pass the PDO_FETCH_ORI_* constants to control the rows fetched from the result set.

PDO_ERR_NONE (string)

Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings.

PDO::beginTransaction --  Initiates a transaction
PDO::commit --  Commits a transaction
PDO::__construct --  Creates a PDO instance representing a connection to a database
PDO::errorCode --  Fetch the SQLSTATE associated with the last operation on the database handle
PDO::errorInfo --  Fetch extended error information associated with the last operation on the database handle
PDO::exec --  Execute an SQL statement and return the number of affected rows
PDO::getAttribute --  Retrieve a database connection attribute
PDO::lastInsertId --  Returns the ID of the last inserted row or sequence value
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 --  Rolls back a transaction
PDO::setAttribute --  Set an attribute
PDOStatement::bindColumn --  Bind a column to a PHP variable
PDOStatement::bindParam --  Binds a parameter to the specified variable name
PDOStatement::bindValue --  Binds a value to a parameter
PDOStatement::closeCursor --  Closes the cursor, enabling the statement to be executed again.
PDOStatement::columnCount --  Returns the number of columns in the result set
PDOStatement::errorCode --  Fetch the SQLSTATE associated with the last operation on the statement handle
PDOStatement::errorInfo --  Fetch extended error information associated with the last operation on the statement handle
PDOStatement::execute --  Executes a prepared statement
PDOStatement::fetch --  Fetches the next row from a result set
PDOStatement::fetchAll --  Returns an array containing all of the result set rows
PDOStatement::fetchColumn --  Returns a single column from the next row of a result set
PDOStatement::getAttribute --  Retrieve a statement attribute
PDOStatement::getColumnMeta --  Returns metadata for a column in a result set
PDOStatement::nextRowset --  Advances to the next rowset in a multi-rowset statement handle
PDOStatement::rowCount --  Returns the number of rows affected by the last SQL statement
PDOStatement::setAttribute --  Set a statement attribute
PDOStatement::setFetchMode --  Set the default fetch mode for this statement
pdo_drivers --  Return an array of available PDO drivers

add a note add a note User Contributed Notes
webform at aouie dot website
28-Sep-2006 02:38
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:
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.
djlopez at gmx dot de
31-Aug-2006 05:56
Please note this:

Won't work:
$sth = $dbh->prepare('SELECT name, colour, calories FROM ?  WHERE calories < ?');

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ?');

The parameter cannot be applied on table names!!
paulius_k at yahoo dot com
25-Jul-2006 11:42
If you need to get Output variable from MSSQL stored procedure, try this :

SET @err = 11

$sth = $dbh->prepare("EXECUTE spReturn_Int ?");
$sth->bindParam(1, $return_value, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
print "procedure returned $return_value\n";
webograph at eml dot cc
13-Jul-2006 07:02
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).
nicolas at serpe dot org
22-May-2006 03:36
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.
pokojny at radlight dot com
23-Apr-2006 11:50
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 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 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) {
call_user_func_array(array(&$this->PDO, $func), $args);
public function prepare() {
$args = func_get_args();
$PDOS = call_user_func_array(array(&$this->PDO, 'prepare'), $args);
           return new
PDOpStatement($this, $PDOS);
public function query() {
$args = func_get_args();
$PDOS = call_user_func_array(array(&$this->PDO, 'query'), $args);
           return new
PDOpStatement($this, $PDOS);
public function exec() {
$args = func_get_args();
call_user_func_array(array(&$this->PDO, 'exec'), $args);
PDOpStatement implements IteratorAggregate {
protected $PDOS;
protected $PDOp;
public function __construct($PDOp, $PDOS) {
$this->PDOp = $PDOp;
$this->PDOS = $PDOS;
public function __call($func, $args) {
call_user_func_array(array(&$this->PDOS, $func), $args);
public function bindColumn($column, &$param, $type=NULL) {
           if (
$type === NULL)
$this->PDOS->bindColumn($column, $param);
$this->PDOS->bindColumn($column, $param, $type);
public function bindParam($column, &$param, $type=NULL) {
           if (
$type === NULL)
$this->PDOS->bindParam($column, $param);
$this->PDOS->bindParam($column, $param, $type);
public function execute() {
$args = func_get_args();
call_user_func_array(array(&$this->PDOS, 'execute'), $args);
public function __get($property) {
public function getIterator() {

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.
keyvez at hotmail dot com
10-Mar-2006 04:49
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: */
= new PDO('mssql:host=sqlserver;dbname=database', 'username',
$ErrorCode = 0;
$Stmt = $Link->prepare('p_sel_all_termlength ?');
"Error = " . $ErrorCode . "\n";

/* PHP Output:
Error = 0
20-Feb-2006 02:16
Below is an example of extending PDO & PDOStatement classes:


class Database extends PDO
parent::__construct('mysql:dbname=test;host=localhost', 'root', '');
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array($this)));

DBStatement extends PDOStatement
public $dbh;

protected function __construct($dbh)
$this->dbh = $dbh;
public function foundRows()
$rows = $this->dbh->prepare('SELECT found_rows() AS rows', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE));
$rowsCount = $rows->fetch(PDO::FETCH_OBJ)->rows;

Dariusz Kielar
13-Feb-2006 02:50
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:
shaolin at adf dot nu
08-Feb-2006 10:18
If your having problems re-compiling PHP with PDO as shared module try this.


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.
tomasz dot wasiluk at gmail dot com
01-Jan-2006 08:09
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...
Matthias Leuffen
04-Dec-2005 05:36
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.

 * 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

         * Attributes (to use in PDO::setAttribute() as 1st Parameter)
const ATTR_ERRMODE = 0;

// Values for ATTR_ERRMODE

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 () {
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 () {
ng4rrjanbiah at rediffmail dot com
16-Mar-2005 02:53
Some useful links on PDO:
1. PDO Wiki ( )
2. Introducing PHP Data Objects ( ), [226 KB], Wez Furlong, 2004-09-24
3. The PHP 5 Data Object (PDO) Abstraction Layer and Oracle ( ), [60.85 KB], Wez Furlong, 2004-07-28
4. PDO - Why it should not be part of core PHP! ( ), Critical review, [38.63 KB], Alan Knowles, 2004-10-22

R. Rajesh Jeba Anbiah