Uploading Images as BLOBS into MySQL

Uploading Images as BLOBS into MySQL

Often I find myself writing applications for clients to store documents as BLOBS in a MySQL database. And, I am always scouring the web for tweaks and enhancements to this process. First of all, obviously, you need to setup your MySQL database table, let's call it "docs." The field that you use for your documents needs to be a LONGBLOB type. I create a simple front-end form to let the user select the file to be uploaded, along with a few ther fields. And then this PHP script does the rest of the work: <%php // GrabFile.php // Form fields from the previous page global $strDesc; global $category; global $fileUpload; // Fields that are automatically generated global $fileUpload_name; global $fileUpload_size; global $fileUpload_type; // Make sure both a description and // file have been entered if(empty($strDesc) || $fileUpload == "none") die("You must enter both a description and file"); // Database connection variables $dbServer = "[YOUR MySQL IP]"; $dbDatabase = "[YOUR DATABASE NAME]"; $dbUser = "[YOUR USERNAME]"; $dbPass = "[YOUR PASSWORD]"; $fileHandle = fopen($fileUpload, "r"); $fileContent = fread($fileHandle, $fileUpload_size); $fileContent = addslashes($fileContent); $sConn = mysql_connect($dbServer, $dbUser, $dbPass) or die("Couldn't connect to database server"); $dConn = mysql_select_db($dbDatabase, $sConn) or die("Couldn't connect to database $dbDatabase"); $dbQuery = "INSERT INTO docs VALUES "; $dbQuery .= "(0, '$strDesc', '$category', '$fileContent', '$fileUpload_type', '$fileUpload_name', '$fileUpload_size')"; mysql_query($dbQuery) or die("Couldn't add file to database"); echo "<h1>File Uploaded Successfully</h1>"; echo "The details of the uploaded file are shown below:<br><br>"; echo "<b>File name:</b> $fileUpload_name <br>"; echo "<b>File type:</b> $fileUpload_type <br>"; echo "<b>File size:</b> $fileUpload_size <br>"; echo "<br><br>"; ?>

Posted: 2007-02-28


Reader Comments


PennComm Family of Websites: JabberGroups Youth Group Manager | JabberText Group Text Messaging | WebOSCenter.com Palm & WebOS News