Upload image into database and retrieve directly from database

upload_form.php
{code codetype=php}
< html>
< head>
< meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
< title>Uploading multiple images
< /head>

< body>
< form action="upload.php" method="post" enctype="multipart/form-data">
Upload these files:
< input name="images[]" type="file" />
< input type="submit" value="Upload Files" />

< /form>
< /body>
< /html>
{/code}

upload.php
{code codetype=php}

< ?php

include "db.php";

$img_count = 0;
foreach ($_FILES["images"]["error"] as $key => $error)
{
// If uplod is successful
if($error == UPLOAD_ERR_OK)
{
$image = chunk_split(base64_encode(file_get_contents($_FILES["images"]['tmp_name'][$key])));
$query = “INSERT INTO photo (image) VALUES(‘$image’)”;
mysql_query($query);
$img_count++;
}
}

echo “< strong>Total images uploaded: “. $img_count;

echo ” < br>Do you want to < a href='showall.php'>< font color='green'>display the uploaded images”;
?>{/code}

showall.php
{code codetype=php}

< html>
< head>
< title>Display all images
< /head>

< body>
< h1>Displaying images from database

< ?php
// include database connection file
include_once "db.php";

$result = mysql_query("SELECT id FROM photo ORDER BY id");
while($row = mysql_fetch_array($result))
{
echo '< p>< img src="image_show.php?id='.$row["id"].'" />‘;
}
?>
< /body>
< /html>?>
< /body>
< /html>
{/code}

image_show.php
{code codetype=php}

< ?php

// include database connection file
include_once "db.php";

header('Content-type: image/jpeg');
$query = "SELECT image from photo where id=". intval($_GET["id"]);
$rs = mysql_fetch_array(mysql_query($query));
echo base64_decode($rs["image"]);
?>
{/code}

Create tables in database
{code codetype=php}
CREATE TABLE `photo` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`image` BLOB NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
{/code}

db.php
{code codetype=php}
< ?php

// change your configuration according to your environment
$mysql_user = "root";
$database_host = "localhost";
$password = "";
$database = "your_database";

$link=mysql_connect($database_host, $mysql_user, $password)
or
die ("Unable to connect to DB server. Error: ".mysql_error());
mysql_select_db($database,$link);

?>
{/code}

No Related Posts

Related Posts with Thumbnails

About the Author

techremind

has written 42 stories on this site.

Copyright © 2013 CoreTimer.com|System Admin's Reference. All rights reserved.