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

Prepared Insert doesn't do anything if ATTR_EMULATE_PREPARES is false

So after a whole lot of struggle with PDO I've narrowed down the root of my problem here. When I set the attribute ATTR_EMULATE_PREPARES to false my insert query runs without error but does not add an entry into the database table. However when I…
4
votes
1 answer

Trouble With Connecting to MSSQL DB

I have an Ubuntu 12.04 server and I'm trying to establish a connection to a MSSQL database. I've managed to connect using tsql and isql, but osql doesn't work and connecting with PHP using PDO also isn't working.. I will try to provide as much…
sudo
  • 43
  • 5
4
votes
1 answer

Where to catch exceptions in a MVC framework

Everyone talks about how important exception handling is. I have never had the need to handle them until recently: try { $pdo = new PDO($dns); } catch (Exception $e) { throw new Exception($e); } Another more general example would be: if…
samland
  • 192
  • 1
  • 12
4
votes
2 answers

Laravel Raw DB Insert Affected Rows

I'm using raw queries with laravel 4, is there a way to check affected rows on an insert? DB::getPdo()->rowCount(); gives me an "undefined method" error. Code is as follows: $query = "INSERT IGNORE INTO table (id) VALUES (?)"; $doQuery =…
Felix
  • 610
  • 2
  • 9
  • 21
4
votes
2 answers

How to delete data from sql with pdo?

Hello I have search the web all day trying to find example of deleting data when I use pdo but all i found its MySQL and MySQLi and I am stuck i can't see what I am missing when I run it it give me /search.php?del=Array(id). This its my code please…
Remus Afrem
  • 87
  • 1
  • 1
  • 7
4
votes
2 answers

PHP PDO ODBC unexpected empty result set

I am trying to track down a problem with using PDO via an ODBC connection to a SQL Server database where I am getting an empty result set for a known good query. I would appreciate any guidance from the community. This is part of a large system that…
calast
  • 41
  • 1
4
votes
2 answers

How to handle user text input in PHP and PDO?

Should I be using PDO quote() and then strip the quotes and slashes from user input when I retrieve it, or is there a better method? When inserting user input into MySQL from a PHP form, any single quotes (apostrophes) are truncating the data. I'm…
raw-bin hood
  • 5,839
  • 6
  • 31
  • 45
4
votes
1 answer

Return Select * from PHP PDO Stored Procedure In MS SQL

For future users: The bottom of this question contains the corrected working code. I know Select * is not the best, but in this example, I am trying to call a stored procedure from php and return the ENTIRE result set so I can loop through the array…
M H
  • 2,179
  • 25
  • 50
4
votes
2 answers

PHP PDO, Return value object after insert query

I tried to search an answer to this question but I couldn't really find it. I have a new value object that is partially filled which I want to insert into the database. When the insert was succesfull I want to return the value object again back to…
Wubinator
  • 741
  • 1
  • 7
  • 16
4
votes
2 answers

MYSQL - PDO with multiple IN clause

I can successfully implement a IN clause within a PDO prepared statement using the following code. in_array = array(1,2,3); $in = str_repeat('?,', count($in_array) - 1) . '?'; $sql = "SELECT * FROM my_table WHERE my_value IN ($in)"; $stm =…
Ka Tech
  • 8,937
  • 14
  • 53
  • 78
4
votes
1 answer

pdo prepare escaping single quotes

I use PDO in a web application I am building. I always thought (I am wrong actually) that using prepare should help with single quotes in the inserted variables but it seems that I miss something. I get an error inserting values like L'Aquila where…
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
4
votes
2 answers

How to use PHP's dblib PDO driver with long usernames? / SQLSTATE[HY000] Name too long for LOGINREC field (severity 2)

I'm trying to connect to a Microsoft SQL Server / Microsoft Azure database with PHP's PDO:
Hauke P.
  • 2,695
  • 1
  • 20
  • 43
4
votes
2 answers

php: loading oracle driver gives error "Unable to load dynamic library - The specified procedure could not be found."

I seem to have a strange problem with PHP. I've migrated a bunch of software from one server to another. On the server some scripts make a connection to Oracle, so to be able to make a connection the oracle client is installed and a tnsnames file…
ErikL
  • 2,031
  • 6
  • 34
  • 57
4
votes
2 answers

First loop restarting in recursive function php

I'm trying to create a series of
    and
  • to create a directory/file structure to navigate some files created from a table in a dB. The table (tb_lib_manual) contains both files and folders. If a record has a null entry for fileID then it is a…
TPJ
  • 51
  • 4
4
votes
1 answer

PHP 5.5.6 Random memory leak

after we have migrated to PHP 5.5.6 and Apache 2.4 from PHP 5.3.3 every site that runs on Kohana 3.3 encounters from time to time a Out of memory exception. Full error message PHP Fatal error: Allowed memory size of 268435456 bytes exhausted…
realshadow
  • 2,599
  • 1
  • 20
  • 38