PDO: Working With BLOBs


PHP Data Objects (PDO) Step By Step Tutorial - Part 11: We can store images or other document into database (such as MySQL). For this job, we will work with BLOB field in table. Ok, let's do it!

First, create a table that have BLOB file. I will create table named "books":

CREATE TABLE `books` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(150) NOT NULL,
  `author` varchar(150) NOT NULL,
  `description` varchar(255) NOT NULL,
  `on_sale` tinyint(1) NOT NULL,
  `cover` blob NOT NULL,
  PRIMARY KEY  (`id`)
);

Sample for insert data:

<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// new data
$title = "ZEND FRAMEWORK TUTORIAL";
$author = "PHP Everyday";
$cover = fopen('7.png','rb');
// query
$sql = "INSERT INTO books (title,author,cover) values(?,?,?)";

$q = $conn->prepare($sql);
$q->bindParam(1, $title);
$q->bindParam(2, $author);
$q->bindParam(3, $cover, PDO::PARAM_LOB);

$q->execute();

?>

Ok, now, this is sample for retrieve data:

<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// query
$sql = "SELECT id,title,author,cover FROM books";
$q = $conn->prepare($sql);
$q->execute();

$q->bindColumn(1, $id);
$q->bindColumn(2, $title);
$q->bindColumn(3, $author);
$q->bindColumn(4, $cover, PDO::PARAM_LOB);

while($q->fetch())
{
file_put_contents($id.".png",$cover);
echo "$title, $author, <img src='".$id.".png'> <br/>";
}

?>

It is clear, isn't it?

Previous: PDO: Prepared Statement and Bound Values
Next: PDO: Alternative Retrieve BLOB Data



Series this article:
PDO: Introduction PHP Data Object
PDO: Activation PHP Data Objects Extension
PDO: Connecting Use PHP Data Object
PDO: Portable Connection to Database
PDO: Posibble Fetch Mode
PDO: Error Handling
PDO: Prepared Statement
PDO: Positional and Named Placeholders
PDO: Insert and Update Statement Use Prepared Statement
PDO: Prepared Statement and Bound Values
PDO: Working With BLOBs
PDO: Alternative Retrieve BLOB Data
PDO: Setting Connection Attributes
PDO: Error Mode Attributes
PDO: Improve Performance with Persistent Connection
PDO: Getting Connection Attributes

Bookmark and Share Tag: PHP Data Objects, PDO, extension, PHP extension, BLOBs Category: PHP Database Post : April 20th 2008 Read: 73,601

advertisements


blog comments powered by Disqus