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

Why can't a PDO object be serialized?

I am making a multi-threaded CLI-PHP application and need to serialize PDO object to pass it between work inside the thread, and wake it up from a sleeping thread using magic methods __sleep() and __wakeup(). However nor the PDO or mysqli extension…
Junior
  • 671
  • 3
  • 9
  • 24
4
votes
3 answers

DELETE multiple rows in PDO

I'm a rookie in PDO and I've done some search about the issue I'm facing and I wasn't able to find any answers about it. As you can see below, I have this function: function deleteInfo($id){ $pdo = connPDO(); $deleteInfo = $pdo ->…
user3854140
  • 43
  • 1
  • 5
4
votes
1 answer

PDO only returns half of the results from mysql

In the following script, I've bound all the parameters using positional offsets to handle the IN clause in PDO. $_POST["group"] is an array. The Chrome Console shows that there are 12 values in the array in Form Data. The number of question marks in…
RedGiant
  • 4,444
  • 11
  • 59
  • 146
4
votes
2 answers

PDO bindValue works for other inputs, why not this one?

I'm building a form where users can update attributes of books. There's a dynamically generated HTML form where users can enter new values for things like "Title", "Author", and "Description" that looks some thing like this: echo "
Eseirt
  • 261
  • 3
  • 11
4
votes
3 answers

Changing time zone after connecting to database using "set time_zone = ..."

I'm trying to change the time zone to "Europe/London" right after connecting to my database. This was my original code: $pdo = new PDO('mysql:host=localhost;dbname=exampletable', 'exampleuser', 'examplepassw', array(\PDO::MYSQL_ATTR_INIT_COMMAND => …
Stan
  • 937
  • 5
  • 15
  • 33
4
votes
3 answers

MYSQL result not returning correctly

So I have a piece of code that will check if you have followed a user or not. And basically let you follow them if you haven't. So here it is if($_SESSION['loggedIn'] == true){ $result = $con->prepare("SELECT * FROM followers WHERE follow_from…
user3537990
4
votes
3 answers

PHP PDO bindParam/bindValue Multiple times

I'm having an issue with the PDO statements for ODBC. I'm using SQL SERVER 7 in Windows Server 2003 and PHP 5.4.x For eg: I have the query: (this is not the actual query but it serves right for the example) $query = SELECT * FROM table WHERE number…
Gabriel Matusevich
  • 3,835
  • 10
  • 39
  • 58
4
votes
2 answers

Rethrowing partially caught exceptions?

I have code that expects to occasionally get a unique index violation when inserting into a remote database. It's not possible to avoid the violation as I need a randomly-generated but human-readable value. Unfortunately PDO just throws a generic…
Code Abominator
  • 1,571
  • 18
  • 23
4
votes
0 answers

Add mysql trigger with PHP PDO

Here is my trigger: DELIMITER // CREATE TRIGGER vf_update_checksum AFTER INSERT ON `vf_params` FOR EACH ROW BEGIN SET @last_param_id = LAST_INSERT_ID(); SET @object_id = (SELECT p.object_id FROM vf_params as p …
ovnia
  • 2,412
  • 4
  • 33
  • 54
4
votes
1 answer

MySQL SELECT Statement Only Returns One Row

It's been quite a long time since I last asked a question, but I've been stumped messing with SQL in an attempt to build my own forum system. The background of my problem is that I'm trying to create a function to display the most popular threads…
Splashsky
  • 139
  • 1
  • 9
4
votes
1 answer

PDO cutting off strings at a UTF-8 character

I am using PHP 5.5 and when I attempt to insert a UTF-8 character in the MySQL database PDO cuts it off at the first non-ASCII character. I have set my connection to be: (DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8', DB_USER,…
Jack M.
  • 1,195
  • 13
  • 30
4
votes
1 answer

SQLSTATE[HY093]: Invalid parameter number

I am having some trouble getting my search query to work. I get this error. SQLSTATE[HY093]: Invalid parameter number Here's my code.
user3566592
  • 71
  • 1
  • 6
4
votes
2 answers

Hash a password and save it and the salt to mysql pdo utf8 encoding

I have this question, excuse me if it is not appropriate, tell me in the comments and I will drop it. The thing is as follows: I generate a salt with this code: $salt = mcrypt_create_iv(32); And the password this way: $password = hash('sha256',…
Bloodraven
  • 61
  • 7
4
votes
2 answers

Can't connect with PDO using ssl but mysqli with ssl works

We set up mysql with SSL by creating the certificates, updating the my.cnf, creating users with right privileges and requiring ssl, restarting the service, and verified it works server side and client side (via mysql command line) by connecting…
fr332lanc3
  • 151
  • 1
  • 11
4
votes
3 answers

Check if username exists PDO

How would I be able to check multiple factors combined instead of checking for each one? So basically I'm using PDO and I have to make sure that the usernames and emails are unique. So how would I do that? I've seen if ( $sthandler->rowCount() > 0…
user3574362
  • 95
  • 1
  • 2
  • 7