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); $stmt...