Robert L Cochran <[EMAIL PROTECTED]> writes:

> 
> Is there open source PHP code (PHP 5.x compatible) that can store and
> retrieve images from an SQLite 3.5.6 database?
> 

Here's a quick example I came up with... it's using sqlite2 (I guess I have an
old version of php or something like that :P), but it should work with an
sqlite 3 database / driver once you change the string that opens the database...

import.php
<?php

function encodeImage($image) {
  $contents = file_get_contents( $image );
  return base64_encode( $contents );
}

try {
  $db = new PDO('sqlite2:test.sqlite');
} catch( PDOException $exception ){
  die('Error: ' . $exception->getMessage());
}

// create page view database table
$db->exec('DROP TABLE images;');
$db->exec('CREATE TABLE images(id, image)');

// insert page visit in database with a prepared statement
$insert_sql = 'INSERT INTO images (image) VALUES (:image)';
$images = array('1.jpg', '2.jpg');

try {
  $i = 1;
  foreach( $images as $image ) {
    echo 'INSERT INTO images (id,image) VALUES (' . $i . ', "' .
encodeImage($image) . '");<br><br>';
    echo '[' . $db->exec('INSERT INTO images (id,image) VALUES (' . $i++ . ', "'
. encodeImage($image) . '");') . ']';
  }
} catch( PDOException $exception ){
  die('Error: ' . $exception->getMessage());
}

?>


List.php
<?php

try {
  $db = new PDO('sqlite2:test.sqlite');
} catch( PDOException $exception ){
  die('Error: ' . $exception->getMessage());
}

foreach ($db->query('SELECT * FROM images;') as $image) {
    echo '<a href="view.php?id=' . $image['id'] . '">View Image ' . $image['id']
. '</a><br>';
    echo $image['image'] . '<br><br>';
}

?>


view.php
<?php

function decodeImage($string) {
  return base64_decode( $string );
}

try {
  $db = new PDO('sqlite2:test.sqlite');
} catch( PDOException $exception ){
  die('Error: ' . $exception->getMessage());
}

define( 'ID', intval( $_REQUEST['id'] ) );

$image = $db->query('SELECT * FROM images;')->fetch();

header( 'Content-type: image/jpg' );
echo decodeImage($image['image']);

?>

_______________________________________________
sqlite-users mailing list
sqlite-users@sqlite.org
http://sqlite.org:8080/cgi-bin/mailman/listinfo/sqlite-users

Reply via email to