Version: 1.0
Type: Sample Code (HOWTO)
Category: Databases
License: GNU Library Public License
Description: Upload image file into mysql.
CREATE TABLE tblimage ( imgid int(3) unsigned NOT NULL auto_increment, imgtype varchar(16) NOT NULL default '', imgdata mediumblob, PRIMARY KEY ( imgid ) ) TYPE=MyISAM; comm.inc -------------------------------------- <? function connectdb(){ mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("strong") or die(mysql_error()); } ?> index.php ---------------------------------- <? if (!isset($submit)) { ?> <form method="POST" action="" enctype=multipart/form-data> <table> <tr><td>Type</td><td><select name="imgtype"><option value="image/gif">GIF</option><option value="image/jpeg">JPEG</option></select></td></tr> <tr><td>File</td><td><input type="file" name="imgfile"></td></tr> <tr><td></td><td><input type="submit" name="submit" value="upload"><input type="reset" value="reset"></td></tr> </table> </form> <? } else { include "../comm.inc"; connectdb(); $hndl=fopen($imgfile,"rb"); $imgdata='': while(!feof($hndl)){ $imgdata.=fread($hndl,2048); } $imgdata=addslashes($imgdata); $sql = "INSERT INTO tblimage VALUES(NULL,'". $imgtype ."','". $imgdata ."')"; @mysql_query($sql) or die(mysql_error()); fclose($hndl); echo "<a href="view.php">view image</a>"; }; ?> post.php ------------------------------------------- <? include "../comm.inc"; connectdb(); $sql = "SELECT imgtype,imgdata FROM tblimage WHERE imgid=". $imgid; $result = @mysql_query($sql) or exit("QUERY FAILED!"); $row=mysql_fetch_object($result); $contenttype = @mysql_result($result,0,"imgtype"); $image = @mysql_result($result,0,"imgdata"); header("Content-type: $row->imgtype"); echo $row->imgdata; ?> view.php ------------------------------------ <? include "../comm.inc"; connectdb(); $sql = "SELECT imgid,imgtype FROM tblimage ORDER BY imgid"; $result = @mysql_query($sql) or die(mysql_error()); echo "<table border=1>n"; echo "<tr><th>imgid</th><th>imgtype</th><th>imgdata</th></tr>n"; while ($rs=mysql_fetch_array($result)) { echo "<tr><td>".$rs[0]."</td>"; echo "<td>".$rs[1]."</td>"; echo "<td><img src="post.php?imgid=".$rs[0]."" width=100 height=100></td></tr>n"; }; echo "</table>n"; ?>