Connecting Tech Pros Worldwide Forums | Help | Site Map

upload, save and edit photo using php

Newbie
 
Join Date: Oct 2006
Posts: 17
#1: Oct 19 '06
hi, can i ask for a very simple example php code on how to save a photo from a form to the database or something like that? and how to get it and display it in the page? i just want a very simple example so that i can understand. i am new with php.

thanks
fariba

Newbie
 
Join Date: Oct 2006
Location: Beside my computer :)
Posts: 13
#2: Oct 19 '06

re: upload, save and edit photo using php


Hi it's my very simple example (4 files named as typed in comments):

First create a database (images) and table in it:
--
-- Database: `images`
--
-- Table structure for table `image`
--

CREATE TABLE `image` (
`id` int(11) NOT NULL auto_increment,
`type` varchar(16) NOT NULL default '',
`stream` blob NOT NULL,
KEY `id` (`id`)
) TYPE=MyISAM;

more create files:

[PHP]
<!-- upload_image.php-->

<form action="insert_image.php" method="post" enctype="multipart/form-data" name="form">
<input type="file" name="file" value="*.*" size="50">
<input type="submit" value="Submit">
</form>
[/PHP]
[PHP]
<!-- insert_image.php-->
<?

$filename = $_FILES['file']['tmp_name'];
if (($handle = fopen($filename, "rb"))) {
$stream = fread($handle, filesize($filename));
fclose($handle);
unlink($_FILES['file']['tmp_name']);
$type = $_FILES['file']['type'];

$dbh = mysql_connect("localhost", "user", "pass");
mysql_select_db("images", $dbh);

$qstr = sprintf("INSERT INTO `image` VALUES ('', '%s', '%s')",
mysql_real_escape_string($type),
mysql_real_escape_string($stream));
mysql_query($qstr, $dbh) or die(mysql_error());
}
header("Location: show_image.php");
?>
[/PHP]
[PHP]
<!-- show_image.php-->

<?

$dbh = mysql_connect("localhost", "user", "pass");
mysql_select_db("images", $dbh);

$qstr = "SELECT `id` FROM `image`";
$res = mysql_query($qstr, $dbh) or die(mysql_error());
while ($row = mysql_fetch_assoc($res)) {
echo 'Image: <img src="image.php?id='.$row["id"].'"><br>';
}

?>
<a href="upload_image.php">Upload more...</a>
[/PHP]
[PHP]
<!-- image.php-->

<?
$dbh = mysql_connect("localhost", "user", "pass");
mysql_select_db("images", $dbh);

$qstr = "SELECT * FROM `image` WHERE `id`=".intval($_REQUEST["id"]);
$result = mysql_query($qstr, $dbh);

if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$type = $row["type"];
header("Content-type: ".$type);
echo $row["stream"];
}
?>

[/PHP]

P.S.
Images no more than 64Kb otherwise field `stream` must be another type.
In strings mysql_connect("localhost", "user", "pass") change "user", "pass" for your value.
Reply