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
3 answers

How can I get outside foreach loop value in this situation?

I am trying to call all the value from a foreach loop from mysql data, and use there value input into another mysql select statement. Look at my code below. It only can gather one value. I was thinking to use the first foreach loop include the whole…
conan
  • 1,327
  • 1
  • 12
  • 27
4
votes
4 answers

Mysql PDO execute always return TRUE

Mysql PDO execute always return true, even if i do a wrong query: try { $sql = $this->db->prepare("INSERT INTO orders (total_price) VALUES ('not_int');"); $result = $sql->execute(); // WHY TRUE?? } catch (Exception $e) { die("Oh noes!…
Vin T
  • 41
  • 1
  • 2
4
votes
1 answer

Php does not recognize PDO_DBLIB driver

So I am writting some code so I can access a Microsft SQL Server. The code I am writting is in a Centos 7 machine. I've installed the php mysql and mssql packages but when I run echo "
", print_r(PDO::getAvailableDrivers()), "
"; I get…
Comum
  • 453
  • 5
  • 21
4
votes
3 answers

Unable to retrieve UTF-8 accented characters from Access via PDO_ODBC

I am trying to get an Access DB converted into MySQL. Everything works perfectly, expect for one big monkey wrench... If the access db has any non standard characters, it wont work. My query will tell me: Incorrect string value: '\xE9d' If I…
Chris6657456456
  • 157
  • 1
  • 2
  • 10
4
votes
4 answers

PHP PDO How does rowCount() get it's results?

Does PHP's PDO run a silent select count(*) statement for it's rowCount() when used after a select statement, or does it get it's result using some other approach? $query = $conn->prepare('select name, alias from accounts where status =…
jmenezes
  • 1,888
  • 6
  • 28
  • 44
4
votes
1 answer

PHP PDO MySQL IN (?,?,?

I want to write a MySQL statement like: SELECT * FROM someTable WHERE someId IN (value1, value2, value3, ...) The trick here is that I do not know ahead of time how many values there will be in the IN(). Obviously I know I can generate the query on…
Nathan H
  • 48,033
  • 60
  • 165
  • 247
4
votes
2 answers

PDO bindParam() PHP Foreach Loop

I have a foreach loop that I would like to execute a prepare statement pdo. I have read a few posts on making a reference but I do not know how to do it with my code: $str = ":City, Aurora; :State, CO"; $wherestr = explode(";",$str); $sql =…
user982853
  • 2,470
  • 14
  • 55
  • 82
4
votes
2 answers

How to fetch values likes PDO::FETCH_COLUMN in Doctrine?

I have the following code: $repository = $this->entitymanager->getRepository('Intlist\Entity\Location'); $query = $repository->createQueryBuilder('l') ->select('l.country') ->groupBy('l.country') ->where('l.country != :empty_country') …
olvlvl
  • 2,396
  • 1
  • 22
  • 22
4
votes
1 answer

PDO Exception "SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens"

I'm not familiar with PDO extension and can't find what's wrong in my code. Code snippet: try { $this->PDO->exec('SET AUTOCOMMIT = 0'); $this->PDO->exec('START TRANSACTION'); …
d7r
  • 107
  • 1
  • 1
  • 12
4
votes
4 answers

My PDO transaction doesn't commit, but also doesn't throw any exception

I have some queries that have run perfectly up until now, but I wanted to wrap them in a transaction to decrease the likelihood of data corruption. After running the code, everything APPEARS to work (i.e. no exception is thrown), but the query is…
manwill
  • 457
  • 4
  • 11
4
votes
3 answers

PDO prepared state not giving same result as manual query

I'm using PHP and PDO prepared statements to access a database. I have this prepared query which I want to execute (multiple times through a foreach-loop, but I don't see that affecting this really): insert into forum_access (forum_id, user_id)…
Danielle
  • 61
  • 4
4
votes
2 answers

Using date range with multiple columns

I have a mysql query prepared to search by date range: select * from active_listings where open_date >= '$start_date' AND open_date <='$end_date' which works excellent. I have two columns in mysql: open_date and next_open_date. How can I do a…
Edward
  • 77
  • 6
4
votes
1 answer

Update query with conditional?

I'm not sure if this possible. If not, let me know. I have a PDO mysql that updates 3 fields. $update = $mypdo->prepare("UPDATE tablename SET field1=:field1, field2=:field2, …
dmontain
  • 1,621
  • 4
  • 14
  • 16
4
votes
1 answer

PHP PDO statement to filter records

I am using PHP PDO to retrieve objects to an iOS app via JSON. There is a database table with event objects. It has three fields to store day, month and year. The owner of the database doesn't want to store dates in a date field, that means that I…
novato
  • 61
  • 9
4
votes
1 answer

Microsoft access with PHP and PDO

I am trying to connect to my access database but cannot. I have on my Microsoft server 2008 with IIS 7. I keep getting this error message. SQLSTATE[IM002] SQLDriverConnect: 0 [Microsoft][ODBC Driver Manager] Data source name not found and no default…
Veronica
  • 541
  • 5
  • 8
  • 20