Book Image

Learning PHP Data Objects

By : Dennis Popel
Book Image

Learning PHP Data Objects

By: Dennis Popel

Overview of this book

PDO is lighter, faster, and more powerful than existing PHP data abstraction interfaces. PDO is a common interface to different databases that must be used with a database-specific PDO driver to access a particular database server: the PDO extension does not provide a database abstraction by itself; it doesn't rewrite SQL, emulate missing database features, or perform any database functions using by itself. It performs the same role as other classic database abstraction layers such as ODBC and JDBC: it's a query abstraction layer that abstracts the mechanism for accessing a database and manipulating the returned records; each database driver that implements the PDO interface can also expose database-specific features as regular extension functions. ¬ PDO ships with PHP 5.1, and is available as an extension for PHP 5.0; it requires the new object-oriented features of PHP 5, and cannot run with earlier versions of PHP.This book will teach you how to use the PDO, including its advanced features. Readers need to be aware of the basics of data abstraction and should be familiar with PHP.
Table of Contents (13 chapters)

Working with BLOBs

Let's now extend our application so that we can upload the books' cover images and display them. Just as with traditional database access, we will use a BLOB field in the books table for this purpose, as well as a varchar field to store the image's MIME type, which we will need to supply to the browser along with the image data. Also, we will need another script that will fetch the image data from the table and pass it to the browser. (We will reference this script from the<img> tag.).

Traditionally, we would not care that we are inserting a BLOB column into the calls to mysql_query() or sqlite_query()—we would just make sure that they are properly quoted. With PDO, however, things are different. PDO works with BLOB columns with the help of streams and prepared statements.

Let's look at the following example:

$blob = fopen('/path/to/file.jpg', 'rb');
$stmt = $conn->prepare("INSERT INTO images(data) VALUES(?)");
$stmt->bindParam(1, $blob, PDO::PARAM_LOB);