Fetching large objects in PHP (PDO)
When you fetch a large object from a result set, rather than treating the large object as a PHP string, you can save system resources by fetching large objects directly into a file on your PHP server.
Before you begin
Procedure
To fetch a large object from the database directly into a file:
- Create a PHP variable representing a stream. For example, assign the return value from a call to the fopen function to a variable.
- Create a PDOStatement object from an SQL statement by calling the PDO::prepare method.
- Bind the output column for the large object to the PHP variable representing the stream by calling the PDOStatement::bindColumn method. The second argument is a string representing the name of the PHP variable that holds the path and name of the file. The third argument is a PHP constant, PDO::PARAM_LOB, which tells the PDO extension to write the data into a file. You must call the PDOStatement::bindColumn method to assign a different PHP variable for every column in the result set.
- Issue the SQL statement by calling the PDOStatement::execute method.
- Call PDOStatement::fetch(PDO::FETCH_BOUND) to retrieve the next row in the result set, binding the column output to the PHP variables that you associated when you called the PDOStatement::bindColumn method.
Example
Fetch a large object from the database directly into a file.
$stmt = $conn->prepare("SELECT name, picture FROM animal_pictures");
$picture = fopen("/opt/albums/spook/grooming.jpg", "wb");
$stmt->bindColumn('NAME', $nickname, PDO::PARAM_STR, 32);
$stmt->bindColumn('PICTURE', $picture, PDO::PARAM_LOB);
$stmt->execute();
$stmt->fetch(PDO::FETCH_BOUND);