Questions tagged [pdo]

PDO (PHP Data Objects) is a data-access abstraction layer (interface) for PHP. It works with most database systems.

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.

Source — https://php.net/manual/en/intro.pdo.php

Connection

PDO uses a DSN to define the connection to the database. It also has a number of connection options which can help you to fine-tune your PDO instance. Some of these options are worth setting by default. Here is an example:

$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);

Let's take a closer look at this code:

  • $dsn contains the database driver (mysql), host (localhost), database name (test), and character set (utf8). Of course, these parameters can be replaced with variables as well.
  • After $dsn comes the username and password.
  • The $opt parameter is an array contains configuration options.

It is recommended to set ERRMODE_EXCEPTION as it will let PDO throw exceptions on errors; this mode is the most reliable way to handle PDO errors.
Setting ATTR_DEFAULT_FETCH_MODE is also a good idea. It saves you having to include it with every fetch, making your application code less bloated.

There are many bad examples around telling you to wrap every PDO statement into try..catch - so, I have to make a distinct note:

DO NOT use the try..catch operator just to handle an error message. Uncaught exceptions are already excellent for this purpose, as they will treat PDO errors in just the same way as other PHP errors - so, you can define the behavior using site-wide settings.
A custom exception handler could be added later, but it is not required. For new users especially, it is recommended to use unhandled exceptions, as they are extremely informative, helpful and secure.
More info...

Prepared statements

Prepared statements are one of the main reasons for using PDO.
The way how it works is explained here: How can prepared statements protect from SQL injection attacks? So, here follows the rules of using PDO:

  • Every dynamic data literal has to be represented in a query by either name (:name) or regular placeholder (?).
  • Every query has to be run in 3 (or 4) steps:
    • prepare() - will prepare the query and create a statement object.
    • bindValue() / bindParam() - this is an optional step as variables can be passed directly into execute().
    • execute() - will actually run the query.
    • fetch* - will return the query result in a usable form.

Some rules of thumb:

  • Use named placeholders only if you need a complex query or if you already have an associative array which keys are equal to table field names. Otherwise, regular placeholders are simpler to use.
  • Use "lazy" binding when possible - passing data into execute will dramatically shorten your code.
  • If you don't know if you need bindValue() or bindParam(), go for the former. bindValue() is less ambiguous and has fewer side effects.

So, here is an example:

$id  = 1;
$stm = $pdo->prepare("SELECT name FROM table WHERE id=?");
$stm->execute(array($id));
$name = $stm->fetchColumn();

Getting results

PDO has some extremely handy methods to return the query result in different formats:

  • fetch() - a general purpose fetch method similar to mysql_fetch_array().
  • fetchAll() to get all the rows without while loop.
  • fetchColumn() to get a single scalar value without getting an array first.

fetchAll() is a very handy function when you make yourself familiar with separating business logic from presentation logic. It lets you get data first and then use it to display:

$stm = $pdo->prepare("SELECT id,name FROM news WHERE dt=curdate()");
$stm->execute();
$data = $stm->fetchAll();

Now we have all the news in the $data array and we can move to presentation part:

?>
<table>
<? foreach ($data as $row): ?>
  <tr>
    <td>
      <a href="news.php?<?=$row['id']?>">
        <?=htmlspecialchars($row['name'])?>
      </a>
    </td>
  </tr>
<? endforeach ?>

Complex cases

Although prepared statements are good things in general, there are some good tips, tricks and pitfalls to know about. First of all, one have to understand that placeholders cannot represent an arbitrary part of the query, but a complete data literal only. Neither part of literal, nor whatever complex expression or a syntax keyword can be substituted with prepared statement.

Here are some typical cases:

PDO Prepared statements and LIKE

Prepare the full literal first:

$name = "%$name%";
$stm  = $pdo->prepare("SELECT * FROM table WHERE name LIKE ?");
$stm->execute(array($name));
$data = $stm->fetchAll();

PDO Prepared statements and LIMIT

When in emulation mode (which is on by default), PDO substitutes placeholders with actual data. And with "lazy" binding (using array in execute()), PDO treats every parameter as a string. As a result, the prepared LIMIT ?,? query becomes LIMIT '10', '10' which is invalid syntax that causes the query to fail.

There are two solutions:

  • Turn emulation off (as MySQL can sort all placeholders out properly).
  • Bind the number explicitly and setting proper type (PDO::PARAM_INT) for this variable.

To turn emulation off, one can run this code (or set in a connection options array):

$conn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

Or to bind these variables explicitly with param type:

$stm = $pdo->prepare('SELECT * FROM table LIMIT ?, ?');
$stm->bindParam(1, $limit_from,PDO::PARAM_INT);
$stm->bindParam(2, $per_page,PDO::PARAM_INT);
$stm->execute();
$data = $stm->fetchAll();

PDO Prepared statements and IN

It is impossible to substitute an arbitrary query part using PDO prepared statements. For such cases as the IN() operator, one must create a set of ?s manually and put them into the query:

$arr = array(1,2,3);
$in  = str_repeat('?,', count($arr) - 1) . '?';
$sql = "SELECT * FROM table WHERE column IN ($in)";
$stm = $db->prepare($sql);
$stm->execute($arr);
$data = $stm->fetchAll();

PDO Prepared statements and identifiers.

PDO has no placeholder for identifiers such as database or table names, so a developer must manually format them. To properly format an identifier, follow these two rules:

  • Enclose identifier in backticks.
  • Escape backticks inside by doubling them.

The code would be:

$table = "`".str_replace("`","``",$table)."`";

After such formatting, it is safe to insert the $table variable into query.

It is also important to always check dynamic identifiers against a list of allowed values. Here is a brief example (from How can I prevent SQL injection in PHP?):

$orders  = array("name","price","qty"); //field names
$key     = array_search($_GET['sort'],$orders); // see if we have such a name
$orderby = $orders[$key]; //if not, first one will be set automatically. smart enuf :)
$query   = "SELECT * FROM `table` ORDER BY $orderby"; //value is safe

another example could be found below:

PDO Prepared statements and INSERT/UPDATE query

(from Insert/update helper function using PDO)
A usual PDO-prepared INSERT query statement consists of 2-5 kilobytes of repeated code, with every field name being repeated six to ten times. Instead, we need a compact helper function to handle a variable number of inserted fields. Of course with face control for these fields, to allow only approved fields into query.

The following code is based on the assumption that HTML form field names are equal to SQL table field names. It is also using the unique MySQL feature of allowing SET statements both for INSERT and UPDATE queries:

function pdoSet($fields, &$values, $source = array()) {
  $set = '';
  $values = array();
  if (!$source) $source = &$_POST;
  foreach ($fields as $field) {
    if (isset($source[$field])) {
      $set.="`".str_replace("`","``",$field)."`". "=:$field, ";
      $values[$field] = $source[$field];
    }
  }
  return substr($set, 0, -2); 
}

This function will produce a correct sequence for the SET operator,

`field1`=:field1,`field2`=:field2

to be inserted into query and $values array for execute().
Can be used this way:

$allowed = array("name","surname","email"); // allowed fields
$sql = "INSERT INTO users SET ".pdoSet($allowed,$values);
$stm = $dbh->prepare($sql);
$stm->execute($values);

Or, for a more complex case:

$allowed = array("name","surname","email","password"); // allowed fields
$_POST['password'] = MD5($_POST['login'].$_POST['password']);
$sql = "UPDATE users SET ".pdoSet($allowed,$values)." WHERE id = :id";
$stm = $dbh->prepare($sql);
$values["id"] = $_POST['id'];
$stm->execute($values);
23916 questions
4
votes
2 answers

Instantiating multiple PHP objects from a single PDO array (without boilerplate)

If you want to get a single object from the database, PDO is pretty helpful: $obj = $handle->fetchAll(PDO::FETCH_CLASS, $obj_name); If you expect multiple class types to be returned in a single row (e.g.: when doing JOINs), PDO is less…
Cosmittus
  • 637
  • 6
  • 19
4
votes
1 answer

Can PDO::MYSQL_ATTR_LOCAL_INFILE be set using config files in Symfony2

Is it possible to set the PDO / Doctrine config in Symfony2 to use PDO::MYSQL_ATTR_LOCAL_INFILE => true without using PDO directly? My use case is loading a csv file into MySQL on Amazon RDS. Symfony version is 2.4 I get the error: PHP Warning: …
codecowboy
  • 9,835
  • 18
  • 79
  • 134
4
votes
1 answer

Simple PDO query returns memory-size error

I tried to make a simple pdo request to select all values of a table stmt = $this->query($query); } ?> But when I call it like $db->query('SELECT * FROM teams'); $teams = $db->resultset();…
sydev
  • 115
  • 1
  • 8
4
votes
1 answer

Try/Catch using Trigger_Error()

I am working on a project with a friend, we are building our own login and registration system for our site which we are creating. I am questioning his skills at coding in PHP with this following code statement: try { $stmt =…
user2313408
4
votes
2 answers

PDO Exception for each statement VS. Once for transaction?

I'm about to implement transactions in my php scripts and I'm doing some testing to help myself understand exactly how they work. I have the following code snippet: try{ $db->beginTransaction(); $update = "UPDATE persons SET first_name =…
A.O.
  • 3,733
  • 6
  • 30
  • 49
4
votes
1 answer

PDOStatement::fetchAll() is too slow

I'm running into a super slow PDOStatement::fetchAll() that is just driving me nuts. My query is running in less than 0.1 seconds. Also in the MySQL terminal, I get my output on my screen in less than 0.1 seconds. But running fetchAll() on the…
ifokkema
  • 49
  • 4
4
votes
1 answer

MySQL FullText Hyphens and Braces return error (ORIGINALLY: PDO prepared statement not doing its job?)

I've updated this question as a perplexing new twist to the problem has shown up. MySQL is not handling hyphens or braces correctly. SELECT * FROM users WHERE MATCH(firstname, lastname, about) AGAINST('-' IN BOOLEAN MODE) returns syntax…
Kevin Pei
  • 5,800
  • 7
  • 38
  • 55
4
votes
3 answers

How to use PDO with PHP 5.5 and MSSQL

I have recently starting to learn PHP, and a few things I'm struggling now is the connection to a MSSQLS database. I learned in some well quoted websites that the most common (and best) way for using a SQL DB with PHP is using PDO. So, this was what…
Nick Spot
  • 257
  • 2
  • 4
  • 12
4
votes
1 answer

How to prevent an id from being modified?

I have developed a bulletin board from scratch using CodeIgniter, PHP, and PDO for MySQL. Now I'm currently cleaning it up and testing for defects / security flaws. I came across a minor defect that I cannot think of a solid solution for. Users can…
Codist
  • 1,198
  • 2
  • 11
  • 28
4
votes
2 answers

PDO Prepared Statement with Int Casting

I am using PDO prepared statements to insert data to database from external xml source, because I do not trust the source 100% I used bindValue on all variables including strings and integers, for example: SQL: INSERT INTO table (id, int1, int2,…
DeepBlue
  • 684
  • 7
  • 23
4
votes
1 answer

PDO : prepare with bindvalue and like %

I've looked over an hour on various website but I couldn't solve my problem. So here is the code that works: $animes = array(); $q = $this->_db->query('SELECT id, nom, nom_id FROM animes WHERE nom LIKE "%code%"'); while ($data =…
Jérôme B
  • 311
  • 5
  • 18
4
votes
2 answers

PDO execute array to string conversion error

I am getting an array to string conversion error when I am trying to run a PDO execute. The execute has to inputs one being a normal string and the other an array. Heres my code: $id = "1"; $array = array("a", "b", "c"); $in =…
user3144542
  • 599
  • 3
  • 9
  • 19
4
votes
3 answers

PHP - PDO fetch resultset with column as index and column as value

Hi i have a table with the following structure +-------------+------+ | date | price| +-------------+------+ | 2014-02-19 | 34 | | 2014-02-20 | 30 | | 2014-02-21 | 28 | +-------------+------+ At present PDO::FETCH_ASSOC returns an…
Maxx
  • 592
  • 18
  • 42
4
votes
4 answers

PHP should I use pg_* functions or PDO?

I'm starting a project using a PostgreSQL database. I know that the mysql_* functions are deprecated and it is best practices to use PDO with MySQL databases, but what about PostgreSQL? Are the pg_* functions deprecated or on their way to being…
jaimelejam
  • 63
  • 1
  • 3
4
votes
1 answer

Error loading pdo_mysql in php built-in server

I want to run php's built-in server (running by $ php -S localhost:8888) with PDO extension. But when I type this command into terminal it gives me: PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php5/20121212/pdo_mysql.so' -…
Cactux
  • 868
  • 1
  • 9
  • 19