0% found this document useful (0 votes)
103 views

Installation: Installing PDO On Unix Systems

The PHP PDO extension provides a lightweight and consistent interface for accessing databases in PHP. It offers a data abstraction layer so the same functions can be used to issue queries and fetch data regardless of the database used. PDO does not rewrite SQL or emulate missing features, instead acting as an abstraction layer. It ships with PHP and drivers must be enabled to connect to specific databases like MySQL or SQLite.

Uploaded by

peso
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views

Installation: Installing PDO On Unix Systems

The PHP PDO extension provides a lightweight and consistent interface for accessing databases in PHP. It offers a data abstraction layer so the same functions can be used to issue queries and fetch data regardless of the database used. PDO does not rewrite SQL or emulate missing features, instead acting as an abstraction layer. It ships with PHP and drivers must be enabled to connect to specific databases like MySQL or SQLite.

Uploaded by

peso
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

PHP PDO

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

Installation
Installing PDO on Unix systems

1. PDO and the PDO_SQLITE driver is enabled by default. You may 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.

Note:
When building PDO as a shared extension (not recommended) then all PDO drivers must be
loaded after PDO itself.

2. When installing PDO as a shared module, the php.ini file needs to be updated 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 pdo.so line, as PDO must be
initialized before the database-specific extensions can be loaded. If you built PDO and the database-
specific extensions statically, you can skip this step.
3. extension=pdo.so
Windows users

1. Choose the other database-specific DLL files and either use dl() to load them at runtime, or enable
them in php.ini below php_pdo.dll. For example:
2. extension=php_pdo.dll
3. extension=php_pdo_firebird.dll
4. extension=php_pdo_informix.dll
5. extension=php_pdo_mssql.dll
6. extension=php_pdo_mysql.dll
7. extension=php_pdo_oci.dll
8. extension=php_pdo_oci8.dll
9. extension=php_pdo_odbc.dll
10. extension=php_pdo_pgsql.dll
11. extension=php_pdo_sqlite.dll
These DLLs should exist in the system's extension_dir.

Note:
Remember that after making changes to your php.ini file you will need to restart PHP for your new
configuration directives to take effect.

Runtime Configuration ¶
The behaviour of these functions is affected by settings in php.ini.

PDO Configuration Options


Name Default Changeable Changelog
pdo.dsn.* php.ini only

Here's a short explanation of the configuration directives.

pdo.dsn.* string

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

Predefined Constants
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.

PDO::PARAM_BOOL (int)
Represents a boolean data type.
PDO::PARAM_NULL (int)
Represents the SQL NULL data type.
PDO::PARAM_INT (int)
Represents the SQL INTEGER data type.
PDO::PARAM_STR (int)
Represents the SQL CHAR, VARCHAR, or other string data type.
PDO::PARAM_STR_NATL (int)
Flag to denote a string uses the national character set. Available since PHP 7.2.0
PDO::PARAM_STR_CHAR (int)
Flag to denote a string uses the regular character set. Available since PHP 7.2.0
PDO::PARAM_LOB (int)
Represents the SQL large object data type.
PDO::PARAM_STMT (int)
Represents a recordset type. Not currently supported by any drivers.
PDO::PARAM_INPUT_OUTPUT (int)
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_DEFAULT (int)
Specifies that the default fetch mode shall be used. Available as of PHP 8.0.7.
PDO::FETCH_LAZY (int)
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. Not valid inside PDOStatement::fetchAll().
PDO::FETCH_ASSOC (int)
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.
PDO::FETCH_NAMED (int)
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 (int)
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 (int)
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 (int)
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.
PDO::FETCH_BOUND (int)
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.
PDO::FETCH_COLUMN (int)
Specifies that the fetch method shall return only a single requested column from the next row in the
result set.
PDO::FETCH_CLASS (int)
Specifies that the fetch method shall return a new instance of the requested class, mapping the
columns to named properties in the class.
Note: The magic __set() method is called if the property doesn't exist in the requested class
PDO::FETCH_INTO (int)
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 (int)
Allows completely customize the way data is treated on the fly (only valid
inside PDOStatement::fetchAll()).
PDO::FETCH_GROUP (int)
Group return by values. Usually combined with PDO::FETCH_COLUMN or PDO::FETCH_KEY_PAIR.
PDO::FETCH_UNIQUE (int)
Fetch only the unique values.
PDO::FETCH_KEY_PAIR (int)
Fetch a two-column result into an array where the first column is a key and the second column is the
value.
PDO::FETCH_CLASSTYPE (int)
Determine the class name from the value of first column.
PDO::FETCH_SERIALIZE (int)
As PDO::FETCH_INTO but object is provided as a serialized string. The class constructor is never
called if this flag is set. Deprecated as of PHP 8.1.0.
PDO::FETCH_PROPS_LATE (int)
Call the constructor before setting properties.
PDO::ATTR_AUTOCOMMIT (int)
If this value is false, PDO attempts to disable autocommit so that the connection begins a
transaction.
PDO::ATTR_PREFETCH (int)
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. A larger prefetch size results in
increased performance at the cost of higher memory usage.
PDO::ATTR_TIMEOUT (int)
Sets the timeout value in seconds for communications with the database.
PDO::ATTR_ERRMODE (int)
See the Errors and error handling section for more information about this attribute.
PDO::ATTR_SERVER_VERSION (int)
This is a read only attribute; it will return information about the version of the database server to which
PDO is connected.
PDO::ATTR_CLIENT_VERSION (int)
This is a read only attribute; it will return information about the version of the client libraries that the
PDO driver is using.
PDO::ATTR_SERVER_INFO (int)
This is a read only attribute; it will return some meta information about the database server to which
PDO is connected.
PDO::ATTR_CONNECTION_STATUS (int)
PDO::ATTR_CASE (int)
Force column names to a specific case specified by the PDO::CASE_* constants.
PDO::ATTR_CURSOR_NAME (int)
Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned
updates.
PDO::ATTR_CURSOR (int)
Selects the cursor type. PDO currently supports
either PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick
with PDO::CURSOR_FWDONLY unless you know that you need a scrollable cursor.
PDO::ATTR_DRIVER_NAME (string)
Returns the name of the driver.

Example #1 using PDO::ATTR_DRIVER_NAME

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
echo "Running on mysql; doing something mysql specific here\n";
}
?>
PDO::ATTR_ORACLE_NULLS (int)
Convert empty strings to SQL NULL values on data fetches.
PDO::ATTR_PERSISTENT (mixed)
Request a persistent connection, rather than creating a new connection. See Connections and
Connection management for more information on this attribute.
PDO::ATTR_STATEMENT_CLASS (int)
Sets the class name of which statements are returned as.
PDO::ATTR_FETCH_CATALOG_NAMES (int)
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. Support of this attribute is at the
driver level; it may not be supported by your driver.
PDO::ATTR_FETCH_TABLE_NAMES (int)
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. Support of this attribute is at the driver
level; it may not be supported by your driver.
PDO::ATTR_STRINGIFY_FETCHES (int)
Forces all values fetched to be treated as strings.
PDO::ATTR_MAX_COLUMN_LEN (int)
Sets the maximum column name length.
PDO::ATTR_DEFAULT_FETCH_MODE (int)
PDO::ATTR_EMULATE_PREPARES (int)
PDO::ATTR_DEFAULT_STR_PARAM (int)
Sets the default string parameter type, this can be one
of PDO::PARAM_STR_NATL and PDO::PARAM_STR_CHAR. Available since PHP 7.2.0.
PDO::ERRMODE_SILENT (int)
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. See Errors and error handling for more information about this
attribute.
PDO::ERRMODE_WARNING (int)
Issue a PHP E_WARNING message if an error occurs. See Errors and error handling for more
information about this attribute.
PDO::ERRMODE_EXCEPTION (int)
Throw a PDOException if an error occurs. See Errors and error handling for more information about
this attribute.
PDO::CASE_NATURAL (int)
Leave column names as returned by the database driver.
PDO::CASE_LOWER (int)
Force column names to lower case.
PDO::CASE_UPPER (int)
Force column names to upper case.
PDO::NULL_NATURAL (int)
PDO::NULL_EMPTY_STRING (int)
PDO::NULL_TO_STRING (int)
PDO::FETCH_ORI_NEXT (int)
Fetch the next row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_PRIOR (int)
Fetch the previous row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_FIRST (int)
Fetch the first row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_LAST (int)
Fetch the last row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_ABS (int)
Fetch the requested row by row number from the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_REL (int)
Fetch the requested row by relative position from the current position of the cursor in the result set.
Valid only for scrollable cursors.
PDO::CURSOR_FWDONLY (int)
Create a PDOStatement object with a forward-only cursor. This is the default cursor choice, as it is the
fastest and most common data access pattern in PHP.
PDO::CURSOR_SCROLL (int)
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. This constant is for your convenience when
checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will
usually know if this is the case by examining the return code from the method that raised the error
condition anyway.
PDO::PARAM_EVT_ALLOC (int)
Allocation event
PDO::PARAM_EVT_FREE (int)
Deallocation event
PDO::PARAM_EVT_EXEC_PRE (int)
Event triggered prior to execution of a prepared statement.
PDO::PARAM_EVT_EXEC_POST (int)
Event triggered subsequent to execution of a prepared statement.
PDO::PARAM_EVT_FETCH_PRE (int)
Event triggered prior to fetching a result from a resultset.
PDO::PARAM_EVT_FETCH_POST (int)
Event triggered subsequent to fetching a result from a resultset.
PDO::PARAM_EVT_NORMALIZE (int)
Event triggered during bound parameter registration allowing the driver to normalize the parameter
name.
PDO::SQLITE_DETERMINISTIC (int)
Specifies that a function created with PDO::sqliteCreateFunction() is deterministic, i.e. it always returns
the same result given the same inputs within a single SQL statement. (Available as of PHP 7.1.4.)

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

Example #1 Connecting to MySQL

<?php
$dbh = 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().

Example #2 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();
}
?>
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 catch statement) or implicitly via set_exception_handler().

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.

Note: If there are still other references to this PDO instance (such as from a PDOStatement instance, or from
other variables referencing the same PDO instance), these have to be removed also (for instance, by
assigning null to the variable that references the PDOStatement).
Example #3 Closing a connection

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here
$sth = $dbh->query('SELECT * FROM foo');

// and now we're done; close it


$sth = null;
$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.

Example #4 Persistent connections

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
?>

The value of the PDO::ATTR_PERSISTENT option is converted to bool (enable/disable persistent


connections), unless it is a non-numeric string, in which case it allows to use multiple persistent connection
pools. This is useful if different connections use incompatible settings, for instance, different values
of PDO::MYSQL_ATTR_USE_BUFFERED_QUERY.

Note:
If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver
options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the
object, the driver will not use persistent connections.
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.

Transactions and auto-commit


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.

Warning
PDO only checks for transaction capabilities on driver level. If certain runtime conditions mean that transactions
are unavailable, PDO::beginTransaction() will still return true without error if the database server accepts the
request to start a transaction.

An example of this would be trying to use transactions on MyISAM tables on a MySQL database.

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 #1 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.

<?php
try {
$dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
array(PDO::ATTR_PERSISTENT => true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}

try {
$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();
}
?>

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. For further reading on
transactions, refer to the documentation provided by your database server.

Prepared statements and stored procedures ¶


Many of the more mature databases support the concept of prepared statements. What are they?
They can be thought of as a kind of compiled template for the SQL that an application wants to
run, that can be customized using variable parameters. Prepared statements offer two major
benefits:

o 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 its plan for executing the query. For complex queries this
process can take up enough time that it will noticeably slow down an application if there
is a need to repeat the same query many times with different parameters. By using a
prepared statement the application avoids repeating the analyze/compile/optimize cycle.
This means that prepared statements use fewer resources and thus run faster.
o The parameters to prepared statements don't need to be quoted; the driver automatically
handles this. If an application exclusively uses prepared statements, the developer can be
sure that no SQL injection will occur (however, if other portions of the query are being
built up with unescaped input, SQL injection is still possible).

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 an application will be able to use the same data access
paradigm regardless of the capabilities of the database.

Example #1 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();
?>

Example #2 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();
?>

Example #3 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 = ?");
$stmt->execute([$_GET['name']]);
foreach ($stmt as $row) {
print_r($row);
}
?>

Example #4 Calling a stored procedure with an output parameter

If the database driver supports it, an application 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 a developer must
know how large a given parameter might be when they bind it. If the value turns out to be larger
than the size they suggested, an error is raised.
<?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";


?>

Example #5 Calling a stored procedure with an input/output parameter

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

<?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";


?>

Example #6 Invalid use of placeholder

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE '%?%'");
$stmt->execute([$_GET['name']]);

// placeholder must be used in the place of the whole value


$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->execute(["%$_GET[name]%"]);
?>
add a note

Errors and error handling ¶


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

o PDO::ERRMODE_SILENT

Prior to PHP 8.0.0, this was 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.
o PDO::ERRMODE_WARNING

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.

o PDO::ERRMODE_EXCEPTION

As of PHP 8.0.0, this is the default mode. 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.

See Exceptions for more information about Exceptions in PHP.

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.

Example #1 Create a PDO instance and set the error mode

<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

?>
Note:
PDO::__construct() will always throw a PDOException if the connection fails regardless of
which PDO::ATTR_ERRMODE is currently set. Uncaught Exceptions are fatal.

Example #2 Create a PDO instance and set the error mode from the constructor

<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'googleguy';
$password = 'googleguy';

/*
Using try/catch around the constructor is still valid even though we set
the ERRMODE to WARNING since
PDO::__construct will always throw a PDOException if the connection fails
.
*/
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ER
RMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}

// This will cause PDO to throw an error of level E_WARNING instead of an exc
eption (when the table doesn't exist)
$dbh->query("SELECT wrongcolumn FROM wrongtable");
?>

The above example will output:

Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146


Table 'test.wrongtable' doesn't exist in
/tmp/pdo_test.php on line 18
add a note

User Contributed Notes

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.

Example #1 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);
?>

Example #2 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();
?>

Example #3 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);

$db->beginTransaction();
$stmt->execute();
$db->commit();
?>
add a note
The PDO class ¶
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

Introduction ¶
Represents a connection between PHP and a database server.

Class synopsis ¶
class PDO {
/* Methods */
public __construct(
string $dsn,
?string $username = null,
?string $password = null,
?array $options = null
)
public beginTransaction(): bool
public commit(): bool
public errorCode(): ?string
public errorInfo(): array
public exec(string $statement): int|false
public getAttribute(int $attribute): mixed
public static getAvailableDrivers(): array
public inTransaction(): bool
public lastInsertId(?string $name = null): string|false
public prepare(string $query, array $options = []): PDOStatement|false
public query(string $query, ?int $fetchMode = null): PDOStatement|false
public query(string $query, ?int $fetchMode = PDO::FETCH_COLUMN, int $colno): PDOStatement|false
public query(
string $query,
?int $fetchMode = PDO::FETCH_CLASS,
string $classname,
array $constructorArgs
): PDOStatement|false
public query(string $query, ?int $fetchMode = PDO::FETCH_INTO, object $object): PDOStatement|false
public quote(string $string, int $type = PDO::PARAM_STR): string|false
public rollBack(): bool
public setAttribute(int $attribute, mixed $value): bool
}

Table of Contents ¶
 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::getAvailableDrivers — Return an array of available PDO drivers
 PDO::inTransaction — Checks if inside a transaction
 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 — Prepares and executes an SQL statement without placeholders
 PDO::quote — Quotes a string for use in a query
 PDO::rollBack — Rolls back a transaction
 PDO::setAttribute — Set an attribute

The PDOStatement class


(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 1.0.0)

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

Class synopsis
class PDOStatement implements IteratorAggregate {
/* Properties */
public string $queryString;
/* Methods */
public bindColumn(
string|int $column,
mixed &$var,
int $type = PDO::PARAM_STR,
int $maxLength = 0,
mixed $driverOptions = null
): bool
public bindParam(
string|int $param,
mixed &$var,
int $type = PDO::PARAM_STR,
int $maxLength = 0,
mixed $driverOptions = null
): bool
public bindValue(string|int $param, mixed $value, int $type = PDO::PARAM_STR): bool
public closeCursor(): bool
public columnCount(): int
public debugDumpParams(): ?bool
public errorCode(): ?string
public errorInfo(): array
public execute(?array $params = null): bool
public fetch(int $mode = PDO::FETCH_DEFAULT, int $cursorOrientation =
PDO::FETCH_ORI_NEXT, int $cursorOffset = 0): mixed
public fetchAll(int $mode = PDO::FETCH_DEFAULT): array
public fetchAll(int $mode = PDO::FETCH_COLUMN, int $column): array
public fetchAll(int $mode = PDO::FETCH_CLASS, string $class, ?array $constructorArgs): array
public fetchAll(int $mode = PDO::FETCH_FUNC, callable $callback): array
public fetchColumn(int $column = 0): mixed
public fetchObject(?string $class = "stdClass", array $constructorArgs = []): object|false
public getAttribute(int $name): mixed
public getColumnMeta(int $column): array|false
public getIterator(): Iterator
public nextRowset(): bool
public rowCount(): int
public setAttribute(int $attribute, mixed $value): bool
public setFetchMode(int $mode): bool
public setFetchMode(int $mode = PDO::FETCH_COLUMN, int $colno): bool
public setFetchMode(int $mode = PDO::FETCH_CLASS, string $class, ?array $constructorArgs): bool
public setFetchMode(int $mode = PDO::FETCH_INTO, object $object): bool
}

Properties
queryString

Used query string.

Changelog
Version Description
8.0.0 PDOStatement implements IteratorAggregate now instead of Traversable.

Table of Contents
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::debugDumpParams — Dump an SQL prepared command
 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 — Fetches the remaining rows from a result set
 PDOStatement::fetchColumn — Returns a single column from the next row of a result set
 PDOStatement::fetchObject — Fetches the next row and returns it as an object
 PDOStatement::getAttribute — Retrieve a statement attribute
 PDOStatement::getColumnMeta — Returns metadata for a column in a result set
 PDOStatement::getIterator — Gets result set iterator
 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

add a note

The PDOException class


(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Introduction
Represents an error raised by PDO. You should not throw a PDOException from your own code.
See Exceptions for more information about Exceptions in PHP.

Class synopsis
class PDOException extends RuntimeException {
/* Properties */
protected int|string $code;
public ?array $errorInfo = null;
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

Properties
errorInfo

Corresponds to PDO::errorInfo() or PDOStatement::errorInfo()

code

SQLSTATE error code. Use Exception::getCode() to access it.


MySQL Functions (PDO_MYSQL) ¶
Introduction ¶
PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to
MySQL databases.

PDO_MYSQL uses emulated prepares by default.

MySQL 8

When running a PHP version before 7.1.16, or PHP 7.2 before 7.2.4, set MySQL 8 Server's default password
plugin to mysql_native_password or else you will see errors similar to The server requested authentication
method unknown to the client [caching_sha2_password] even when caching_sha2_password is not used.

This is because MySQL 8 defaults to caching_sha2_password, a plugin that is not recognized by the older PHP
(mysqlnd) releases. Instead, change it by
setting default_authentication_plugin=mysql_native_password in my.cnf.
The caching_sha2_password plugin will be supported in a future PHP release. In the meantime,
the mysql_xdevapi extension does support it.

Warning
Beware: Some MySQL table types (storage engines) do not support transactions. When writing transactional
database code using a table type that does not support transactions, MySQL will pretend that a transaction was
initiated successfully. In addition, any DDL queries issued will implicitly commit any pending transactions.
Note:
The MySQL driver does not properly
support PDO::PARAM_INPUT_OUTPUT via PDOStatement::bindParam(); while such parameters can be
used, they are not updated (i.e. the actual output is ignored).

Installation ¶
The common Unix distributions include binary versions of PHP that can be installed. Although these binary
versions are typically built with support for the MySQL extensions, the extension libraries themselves may need
to be installed using an additional package. Check the package manager than comes with your chosen
distribution for availability.

For example, on Ubuntu the php5-mysql package installs the ext/mysql, ext/mysqli, and PDO_MYSQL PHP
extensions. On CentOS, the php-mysql package also installs these three PHP extensions.

Alternatively, you can compile this extension yourself. Building PHP from source allows you to specify the
MySQL extensions you want to use, as well as your choice of client library for each extension.

When compiling, use --with-pdo-mysql[=DIR] to install the PDO MySQL extension, where the
optional [=DIR] is the MySQL base library. Mysqlnd is the default library. For details about choosing a library,
see Choosing a MySQL library.

Optionally, the --with-mysql-sock[=DIR] sets to location to the MySQL unix socket pointer for all MySQL
extensions, including PDO_MYSQL. If unspecified, the default locations are searched.

Optionally, the --with-zlib-dir[=DIR] is used to set the path to the libz install prefix.
$ ./configure --with-pdo-mysql --with-mysql-sock=/var/mysql/mysql.sock

SSL support is enabled using the appropriate PDO_MySQL constants, which is equivalent to calling
the » MySQL C API function mysql_ssl_set(). Also, SSL cannot be enabled with PDO::setAttribute because the
connection already exists. See also the MySQL documentation about » connecting to MySQL with SSL.

Predefined Constants ¶
The constants below are defined by this driver, and will only be available when the extension has been either
compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be
used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected
behaviour. PDO::getAttribute() may be used to obtain the PDO::ATTR_DRIVER_NAME attribute to check the
driver, if your code can run against multiple drivers.

PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (int)
If this attribute is set to true on a PDOStatement, the MySQL driver will use the buffered versions of
the MySQL API. If you're writing portable code, you should use PDOStatement::fetchAll() instead.

Example #1 Forcing queries to be buffered in mysql

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
$stmt = $db->prepare('select * from foo',
array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
} else {
die("my application only works with mysql; I should use \$stmt-
>fetchAll() instead");
}
?>
PDO::MYSQL_ATTR_LOCAL_INFILE (int)

Enable LOAD LOCAL INFILE. Available as of PHP 8.1.0.

Note, this constant can only be used in the driver_options array when constructing a new
database handle.

PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY (string)

Allows restricting LOCAL DATA loading to files located in this designated directory.

Note, this constant can only be used in the driver_options array when constructing a new
database handle.

PDO::MYSQL_ATTR_INIT_COMMAND (string)

Command to execute when connecting to the MySQL server. Will automatically be re-executed when
reconnecting.

Note, this constant can only be used in the driver_options array when constructing a new
database handle.

PDO::MYSQL_ATTR_READ_DEFAULT_FILE (int)
Read options from the named option file instead of from my.cnf. This option is not available if mysqlnd
is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_READ_DEFAULT_GROUP (int)

Read options from the named group from my.cnf or the file specified
with MYSQL_READ_DEFAULT_FILE. This option is not available if mysqlnd is used, because
mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_MAX_BUFFER_SIZE (int)

Maximum buffer size. Defaults to 1 MiB. This constant is not supported when compiled against
mysqlnd.

PDO::MYSQL_ATTR_DIRECT_QUERY (int)

Perform direct queries, don't use prepared statements.

PDO::MYSQL_ATTR_FOUND_ROWS (int)

Return the number of found (matched) rows, not the number of changed rows.

PDO::MYSQL_ATTR_IGNORE_SPACE (int)

Permit spaces after function names. Makes all functions names reserved words.

PDO::MYSQL_ATTR_COMPRESS (int)

Enable network communication compression.

PDO::MYSQL_ATTR_SSL_CA (int)

The file path to the SSL certificate authority.

PDO::MYSQL_ATTR_SSL_CAPATH (int)

The file path to the directory that contains the trusted SSL CA certificates, which are stored in PEM
format.

PDO::MYSQL_ATTR_SSL_CERT (int)

The file path to the SSL certificate.

PDO::MYSQL_ATTR_SSL_CIPHER (int)

A list of one or more permissible ciphers to use for SSL encryption, in a format understood by
OpenSSL. For example: DHE-RSA-AES256-SHA:AES128-SHA

PDO::MYSQL_ATTR_SSL_KEY (int)

The file path to the SSL key.


PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT (int)

Provides a way to disable verification of the server SSL certificate.

This exists as of PHP 7.0.18 and PHP 7.1.4.

PDO::MYSQL_ATTR_MULTI_STATEMENTS (int)

Disables multi query execution in both PDO::prepare() and PDO::query() when set to false.

Note, this constant can only be used in the driver_options array when constructing a new
database handle.

Runtime Configuration ¶
The behaviour of these functions is affected by settings in php.ini.

PDO_MYSQL Configuration Options


Name Default Changeable
pdo_mysql.default_socket "/tmp/mysql.sock" PHP_INI_SYSTEM
pdo_mysql.debug NULL PHP_INI_SYSTEM
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

pdo_mysql.default_socket string

Sets a Unix domain socket. This value can either be set at compile time if a domain socket is found at
configure. This ini setting is Unix only.

pdo_mysql.debug bool

Enables debugging for PDO_MYSQL. This setting is only available when PDO_MYSQL is compiled
against mysqlnd and in PDO debug mode.

Table of Contents ¶
 PDO_MYSQL DSN — Connecting to MySQL databases

You might also like