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
1 answer

how to set the connection with a schema in a Postgresql DB with PDO PHP

If I have a Postgresql DB with several Schemas and I want to set a connection with my Web App to one of this shemas (not public schema by default) of the DB using PDO, what will be the most optimal way? The connection with the DB I do currently like…
zgrizzly_7
  • 773
  • 2
  • 10
  • 22
4
votes
2 answers

PHP PDO Convert array to different format

I am trying to convert an array obtained by the code below using non-deprecated techniques with php pdo: $stm = $conn->prepare("SELECT * FROM mysqltable"); $stm->execute(); $results = $stm->fetchAll(PDO::FETCH_ASSOC); print_r($results); to the…
newpie
  • 77
  • 8
4
votes
1 answer

Could not find PDO driver when installing laravel 5 on CentOS 7 with DigitalOcean

I'm trying to get my offline Laravel 5 webapp deployed. First of all I created a new droplet at DigitalOcean. Via ssh access I installed a fully working LAMP stack (I got the apache test-page at my ip-address). After that, I pulled my git repo into…
4
votes
2 answers

How does the PDO prepared statements works “inside”?

Prepared statements are useful because preparing "templates" to add the data prevents SQL injections, my question is, how is this possible? How do prepared statements really work? After I write a query, bound the params and executed the query, what…
Francesco
  • 555
  • 4
  • 23
4
votes
1 answer

october cms could not find driver

First off I just want to preface that I am on shared hosting on justhost.com so I am not excluding them as a possible culprit and minimal proper PDO support. I just know that the site worked for a while before the error, and very little changed. I…
Eli Baird
  • 98
  • 1
  • 6
4
votes
2 answers

new PDO refuses to work

I want to create a sqlite database with these lines: "; try { $db_connection = new PDO('sqlite:file.db'); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } echo "there
"; ?> After that I…
steffen
  • 8,572
  • 11
  • 52
  • 90
4
votes
1 answer

Using closures in encapsulating PDO transactions does not work. Why?

I'm currently having a problem in encapsulating PDO transactions for ease of use; after the transaction is executed, there is NO database changes that happened! My idea was to just provide the parameters and callable transaction needed to be…
Xegara
  • 103
  • 1
  • 7
  • 18
4
votes
0 answers

How to connect MySQL from PDO under SSL

I have configured MySQL SSL in ubuntu server. show variables like "%ssl%"; +---------------+----------------------------+ | Variable_name | Value | +---------------+----------------------------+ | have_openssl | YES …
RNK
  • 5,582
  • 11
  • 65
  • 133
4
votes
2 answers

PHP PDO (MSSQL) can not get OUPUT parameters

I'm trying to get OUTPUT using bindParam (PHP PDO). The PHP PDO library is the FreeTDS for MS SQL driver. Whatever I do, I can't seem to get the "OUTPUT" in the the bound params as suggested on php.net. I've verified I can call the EXEC and return a…
jjwdesign
  • 3,272
  • 8
  • 41
  • 66
4
votes
2 answers

Does the mysql client package version on webserver affect PHP queries?

I have two RHEL servers, one to host the PHP application, one to host the MySQL server. Database server has MySQL Enterprise version 5.6.21 installed. While getting the application server built, I asked that the rpm…
maafk
  • 6,176
  • 5
  • 35
  • 58
4
votes
1 answer

PDO SUM MYSQL table

I am learning as i go and been picking up snippets of code as i go and been working on this for the past few days and now i have thrown the towel in to seek help. I am trying to calculate the sum of 2 columns in my database using PDO. here is my…
4
votes
1 answer

Unable to insert false value in Boolean type - getting casted to empty string

I've this column in MySql: male BOOLEAN COMMENT "true for male", I'm using this query to insert using PDO wrapper in Drupal: $id = db_insert('Person')->fields(array( ....... 'male' => false, ) )->execute(); I'm…
user5858
  • 1,082
  • 4
  • 39
  • 79
4
votes
5 answers

Is it better/faster to do a multi insert or a many different insert in a pdo prepared statement?

i need to insert 1000-30000 lines at a time (made of 19 elements each) into a mysql table from php using pdo prepared statements. I was asking myself if it would be better to do many different inserts or one big multi insert, like: INSERT INTO table…
Gotrekk
  • 494
  • 2
  • 15
4
votes
2 answers

If data exists in mysql database use it else use placeholder data

What i want to do is to display some data from mysql database if its set by user and if it not set then i just want to display some placeholder or "dummy" data. For example if user create profile he will by default get some random or placeholder…
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
4
votes
0 answers

PDO 'localhost' very slow

I have set up a local server using 'Uniform Server Z'. It suits my needs better than WAMP and XAMPP. I am very happy with it apart from 1 thing - it's very slow. It takes over 2 seconds between request and download for any of my webpages. I realised…
hedgehog90
  • 1,402
  • 19
  • 37