Tuesday, July 28, 2009

How can uploading of pictures be implemented using PHP and MySQL and what data type can contain pictures?

I’ve been told to develop a software that would enable users to upload and view the contents of a database. I’ve succeeded in the viewing aspect of the software but I’m having problem implementing the uploading of pictures in the software.

How can uploading of pictures be implemented using PHP and MySQL and what data type can contain pictures?
Micro-tutorial:





HTML Upload Form:





%26lt;html%26gt;


%26lt;head%26gt;


%26lt;title%26gt;Upload File%26lt;/title%26gt;


%26lt;/head%26gt;


%26lt;body%26gt;


%26lt;form enctype="multipart/form-data"





action="upfile.php" method="post"%26gt;


%26lt;br%26gt;


Type or browse Filename:


%26lt;input type="file" name="userfile"%26gt;


%26lt;input type="submit" value="Upload File"%26gt;


%26lt;/form%26gt;


%26lt;/body%26gt;


%26lt;/html%26gt;





PHP handler upfile.php:





%26lt;html%26gt;


%26lt;head%26gt;


%26lt;title%26gt;Upload Handler%26lt;/title%26gt;


%26lt;/head%26gt;


%26lt;body%26gt;


%26lt;?php








if(is_uploaded_file($_FILES['userfile'...





])) {


if($_FILES['userfile']['size'] %26lt; $maxsize) {


$imgData =addslashes





(file_get_contents($_FILES['userfile']...





));


$size =





getimagesize($_FILES['userfile']['tmp_...





mysql_connect("localhost", "$username",





"$password") OR DIE (mysql_error());





mysql_select_db ("$dbname") OR DIE ("Unable to





select db".mysql_error());





$sql = "INSERT INTO images (image_id,





image_type,image,image_size,image_name... VALUES





('','{$size['mime']}','{$imgData}',





'{$size[3]}','{$_FILES['userfile']['na...





if(!mysql_query($sql)) {


echo 'Unable to upload file';


}


?%26gt;





%26lt;/body%26gt;


%26lt;/html%26gt;





The MySQL table will need a field called Image (or





whatever) with one of these blob types:


BLOB


TINYBLOB


MEDIUMBLOB


LONGBLOB





...as well as other useful fields:





create table images


(


image_id tinyint(3) not null,


image_type varchar(25) not null,


image blob not null,


image_size varchar(25) not null,


image_ctgy varchar(25) not null,


image_name varchar(50) not null


);





Retrieving and returning an image:





%26lt;?php


$link = mysql_connect("localhost", "username",





"password") or die("Could not connect: " .





mysql_error());


mysql_select_db("images") or die(mysql_error());


$sql = "SELECT image FROM images WHERE





image_id=0";


$result = mysql_query($sql) or die("Invalid





query: " . mysql_error());


header("Content-type: image/jpeg");


echo mysql_result($result, 0);


mysql_close($link);


?%26gt;
Reply:Maybe this will help. http://www.php.net/manual/en/features.fi...





If not, what exactly are you having trouble with?

flower arranging

No comments:

Post a Comment