webguync Posted November 15, 2010 Share Posted November 15, 2010 Hi, I need some assistance with coding a form to upload a picture into MySQL DB. This will be part of a form and have a field where the user can upload a picture from where-ever, click submit and the image is uploaded into MySQL. If anyone has done this and can offer assistance with the html coding, PHP and how to set the field in MySQL, I would be greatly appreciative. Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/ Share on other sites More sharing options...
ManiacDan Posted November 15, 2010 Share Posted November 15, 2010 Don't store the image in mysql, store it on the filesystem and store the PATH in mysql. Any file upload tutorial will work. Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1134701 Share on other sites More sharing options...
joel24 Posted November 15, 2010 Share Posted November 15, 2010 As ManiacDan said, uploading the file and storing a path in mysql is much better as storing the binary data of the image in mysql, reading this and then displaying as an image puts a lot of unnecessary strain on the db/server. Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1134703 Share on other sites More sharing options...
webguync Posted November 16, 2010 Author Share Posted November 16, 2010 ok, I have researched and found some tutorials on creating a file upload form to store files in a directory on the server. Still fuzzy about how to store the URL to this directory in MySQL after the file is successfully uploaded. I was hoping to do this automatically of course and not manually. Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1135091 Share on other sites More sharing options...
ManiacDan Posted November 16, 2010 Share Posted November 16, 2010 I was hoping to do this automatically of course and not manually.This kind of quote makes my head hurt. You ARE doing it automatically: you're telling a computer how to do the work for you. Write this program once, and it will execute 100,000,000 times without you having to do anything.  That being said, at some point in your script you have the filename of the image in a string (since you have to call move_uploaded_file on it). Store that filename in the database.  -Dan Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1135095 Share on other sites More sharing options...
litebearer Posted November 16, 2010 Share Posted November 16, 2010 http://www.tizag.com/phpT/fileupload.php Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1135100 Share on other sites More sharing options...
webguync Posted November 17, 2010 Author Share Posted November 17, 2010 I found a script I like, and the file seems to upload ok, but I don't see where the file gets uploaded to. I believe the script is supposed to create a new directory called files, but don't see it?  <?php /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ jqUploader serverside example: (author : pixeline, http://www.pixeline.be) when javascript is available, a variable is automatically created that you can use to dispatch all the possible actions This file examplifies this usage: javascript available, or non available. 1/ a form is submitted 1.a javascript is off, so jquploader could not be used, therefore the file needs to be uploaded the old way 1.b javascript is on, so the file, by now is already uploaded and its filename is available in the $_POST array sent by the form 2/ a form is not submitted, and jqUploader is on jqUploader flash file is calling home! process the upload. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ $uploadDir = dirname(__FILE__) . '/files/'; $uploadFile = $uploadDir . basename($_FILES['Filedata']['name']); if ($_POST['submit'] != '') {   // 1. submitting the html form   if (!isset($_GET['jqUploader'])) {     // 1.a javascript off, we need to upload the file     if (move_uploaded_file ($_FILES[0]['tmp_name'], $uploadFile)) {       // delete the file       // @unlink ($uploadFile);       $html_body = '<h1>File successfully uploaded!</h1><pre>';       $html_body .= print_r($_FILES, true);       $html_body .= '</pre>';     } else {       $html_body = '<h1>File upload error!</h1>';       switch ($_FILES[0]['error']) {         case 1:           $html_body .= 'The file is bigger than this PHP installation allows';           break;         case 2:           $html_body .= 'The file is bigger than this form allows';           break;         case 3:           $html_body .= 'Only part of the file was uploaded';           break;         case 4:           $html_body .= 'No file was uploaded';           break;         default:           $html_body .= 'unknown errror';       }       $html_body .= 'File data received: <pre>';       $html_body .= print_r($_FILES, true);       $html_body .= '</pre>';     }     $html_body = '<h1>Full form</h1><pre>';     $html_body .= print_r($_POST, true);     $html_body .= '</pre>';   } else {     // 1.b javascript on, so the file has been uploaded and its filename is in the POST array     $html_body = '<h1>Form posted!</h1><p>Error:<pre>';     $html_body .= print_r($_POST, false);     $html_body .= '</pre>';   }   myHtml($html_body); } else {   if ($_GET['jqUploader'] == 1) {     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++     // 2. performing jqUploader flash upload     if ($_FILES['Filedata']['name']) {       if (move_uploaded_file ($_FILES['Filedata']['tmp_name'], $uploadFile)) {         // delete the file         // @unlink ($uploadFile);         return $uploadFile;       }     } else {       if ($_FILES['Filedata']['error']) {         return $_FILES['Filedata']['error'];       }     }   } } // /////////////////// HELPER FUNCTIONS function myHtml($bodyHtml) {   ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jqUploader demo - Result</title> <link rel="stylesheet" type="text/css" media="screen" href="style.css"/> </head> <body> <?php echo $bodyHtml;   ?> </body> </html> <?php } ?> Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1135552 Share on other sites More sharing options...
ManiacDan Posted November 17, 2010 Share Posted November 17, 2010 No, it expects the directory to already be there. Make it, and this script should start working.  Also, the move_uploaded_file function should be throwing errors, you probably have error-reporting turned off.  -Dan Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1135612 Share on other sites More sharing options...
webguync Posted November 17, 2010 Author Share Posted November 17, 2010 ok, great. Thanks, seems to be working ok now. The only other part I need assistance with in regards to the subject title is creating a path to the image file in MySQL after the upload takes place. Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1135619 Share on other sites More sharing options...
ManiacDan Posted November 17, 2010 Share Posted November 17, 2010     if (move_uploaded_file ($_FILES[0]['tmp_name'], $uploadFile)) {       mysql_query("insert into filenames (filename) values ('{$uploadFile}')"); Just like I said earlier, you're using move_uploaded_file, which accepts the new filename. Insert that filename into the DB.  -Dan Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1135649 Share on other sites More sharing options...
webguync Posted November 18, 2010 Author Share Posted November 18, 2010 sorry, but still trying to understand the best way to do this. I have a form which submits basic info such as name, username,password email address etc. which works and then I have a form with the image upload which works, but I would like to have just one form which submits to one table in MySQL with he path to the file. I think there is a way to combine the two, but I tried and it doesn't work.  the respective form code and PHP files are below.  <form enctype="multipart/form-data" action="flash_upload.php" method="POST" class="a_form">   <fieldset>   <legend>Upload your profile picture</legend>   <ol>    <li id="example3">     <label for="FileUpload">Choose a file to upload:</label>     <input name="myfile" id="FileUpload" type="file" />    </li>   </ol>   </fieldset>    </form> <form id="ContactForm" action="">       <fieldset>         <p>           <label>First Name</label>           <input id="FirstName" name="FirstName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span>         </p>         <p>           <label>Last Name</label>           <input id="LastName" name="LastName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span>         </p>         <p>           <label>User Name</label>           <input id="UserName" name="UserName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span>         </p>         <p>           <label>Password</label>           <input type="password" id="Password" name="Password" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span>         </p>         <p>           <label>Email</label>           <input id="email" name="email" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span>         </p>         <p>           <label>Zip Code</label>           <input id="Zip" name="Zip" class="inplaceError" maxlength="12" type="text" autocomplete="off"/>           <span class="error" style="display:none;"></span>         </p>         <p>           <label>Birthday (mm/dd/yyyy format)</label>           <input id="Birthday" name="Birthday" class="inplaceError" maxlength="12" type="text" autocomplete="off"/>           <span class="error" style="display:none;"></span>         </p>          <p>           <label>Security Question</label>           <input id="Security" name="Security" class="inplaceError" maxlength="255" type="text" autocomplete="off"/>           <span class="error" style="display:none;"></span>         </p>               <input id="newcontact" name="newcontact" type="hidden" value="1"></input>         <p class="submit">           <input id="send" type="button" value="Join"/>           <span id="loader" class="loader" style="display:none;"></span> <span id="success_message" class="success"></span>           <span id="success_message" class="fail"></span>                  </p>         </fieldset>       </form> <?php ini_set("display_errors","1"); ERROR_REPORTING(E_ALL); require_once("db.php"); /* Database Class */ require_once('utils/is_email.php'); /* Email Validation Script */ /* Handle Ajax Request */ if(isset($_POST['newcontact'])){ $contact = new Contact(); unset($contact); } else{ header('Location: /'); } /* Class Contact */ class Contact{ private $db; /* the database obj */ private $errors = array(); /* holds error messages */ private $num_errors; /* number of errors in submitted form */ public function __construct(){ $this->db = new DB(); if(isset($_POST['newcontact'])) $this->processNewMessage(); else header("Location: /"); } public function processNewMessage(){ $email = $_POST['email']; $FirstName = $_POST['FirstName']; $LastName = $_POST['LastName']; $UserName = $_POST['UserName']; $Password = $_POST['Password']; $Zip = $_POST['Zip']; $Birthday = $_POST['Birthday']; $Security = $_POST['Security']; /* Server Side Data Validation */ /* Email Validation */ if(!$email || mb_strlen($email = trim($email)) == 0) $this->setError('email','required field'); else{ if(!is_email($email)) $this->setError('email', 'invalid email'); else if(mb_strlen($email) > 120) $this->setError('email', 'too long! 120'); } /* FirstName Validation */ if(!$FirstName || mb_strlen($FirstName = trim($FirstName)) == 0) $this->setError('FirstName', 'required field'); else if(mb_strlen(trim($FirstName)) > 120) $this->setError('FirstName', 'too long! 120 characters'); /* LastName Validation */ if(!$LastName || mb_strlen($LastName = trim($LastName)) == 0) $this->setError('LastName', 'required field'); else if(mb_strlen(trim($LastName)) > 120) $this->setError('LastName', 'too long! 120 characters'); /* UserName Validation */ if(!$UserName || mb_strlen($UserName = trim($UserName)) == 0) $this->setError('UserName', 'required field'); else if(mb_strlen(trim($UserName)) > 120) $this->setError('UserName', 'too long! 120 characters'); /* Password Validation */ if(!$Password || mb_strlen($Password = trim($Password)) == 0) $this->setError('Password', 'required field'); else if(mb_strlen(trim($Password)) > 120) $this->setError('Password', 'too long! 120 characters'); /* zip code Validation */ if(!$Zip || mb_strlen($Zip = trim($Zip)) == 0) $this->setError('Zip', 'required field'); else if(mb_strlen(trim($Zip)) > 120) $this->setError('Zip', 'too long! 120 characters'); /* Message Validation */ $Birthday = trim($Birthday); if(!$Birthday || mb_strlen($Birthday = trim($Birthday)) == 0) $this->setError('Birthday','required field'); elseif(mb_strlen($Birthday) > 300) $this->setError('Birthday', 'too long! 300 characters'); /* Message Validation */ $Security = trim($Security); if(!$Security || mb_strlen($Security = trim($Security)) == 0) $this->setError('Security','required field'); elseif(mb_strlen($Security) > 300) $this->setError('Security', 'too long! 300 characters'); /* Errors exist */ if($this->countErrors() > 0){ $json = array( 'result' => -1, 'errors' => array( array('name' => 'email' ,'value' => $this->error_value('email')), array('name' => 'FirstName' ,'value' => $this->error_value('FirstName')), array('name' => 'LastName' ,'value' => $this->error_value('LastName')), array('name' => 'UserName' ,'value' => $this->error_value('UserName')), array('name' => 'Password' ,'value' => $this->error_value('Password')), array('name' => 'Zip'  ,'value' => $this->error_value('Zip')), array('name' => 'Birthday' ,'value' => $this->error_value('Birthday')), array('name' => 'Security' ,'value' => $this->error_value('Security')), ) ); $encoded = json_encode($json); echo $encoded; unset($encoded); } /* No errors, insert in db*/ else{ if(($ret = $this->db->dbNewMessage($email, $FirstName, $LastName,$UserName, $Password, $Zip, $Birthday, $Security)) > 0){ $json = array('result' => 1); if(SEND_EMAIL) $this->sendEmail($email,$name,$website,$message); } else $json = array('result' => -2); /* something went wrong in database insertion */ $encoded = json_encode($json); echo $encoded; unset($encoded); } } public function sendEmail($email,$name,$website,$message){ /* Just format the email text the way you want ... */ $message_body = "Hi, ".$name."(".$email." - ".$website.") sent you a message from yoursite.com\n" ."email: ".$email."\n" ."message: "."\n" .$message; $headers = "From: ".EMAIL_FROM_NAME." <".EMAIL_FROM_ADDR.">"; return mail(EMAIL_TO,MESSAGE_SUBJECT,$message_body,$headers); } public function setError($field, $errmsg){ $this->errors[$field] = $errmsg; $this->num_errors = count($this->errors); } public function error_value($field){ if(array_key_exists($field,$this->errors)) return $this->errors[$field]; else return ''; } public function countErrors(){ return $this->num_errors; } }; ?>  <?php $uploadDir = dirname(__FILE__) . '/files/'; $uploadFile = $uploadDir . basename($_FILES['Filedata']['name']); if ($_POST['submit'] != '') {   // 1. submitting the html form   if (!isset($_GET['jqUploader'])) {     // 1.a javascript off, we need to upload the file     if (move_uploaded_file ($_FILES[0]['tmp_name'], $uploadFile)) {       // delete the file       // @unlink ($uploadFile);       $html_body = '<h1>File successfully uploaded!</h1><pre>';       $html_body .= print_r($_FILES, true);       $html_body .= '</pre>';     } else {       $html_body = '<h1>File upload error!</h1>';       switch ($_FILES[0]['error']) {         case 1:           $html_body .= 'The file is bigger than this PHP installation allows';           break;         case 2:           $html_body .= 'The file is bigger than this form allows';           break;         case 3:           $html_body .= 'Only part of the file was uploaded';           break;         case 4:           $html_body .= 'No file was uploaded';           break;         default:           $html_body .= 'unknown errror';       }       $html_body .= 'File data received: <pre>';       $html_body .= print_r($_FILES, true);       $html_body .= '</pre>';     }     $html_body = '<h1>Full form</h1><pre>';     $html_body .= print_r($_POST, true);     $html_body .= '</pre>';   } else {     // 1.b javascript on, so the file has been uploaded and its filename is in the POST array     $html_body = '<h1>Form posted!</h1><p>Error:<pre>';     $html_body .= print_r($_POST, false);     $html_body .= '</pre>';   }   myHtml($html_body); } else {   if ($_GET['jqUploader'] == 1) {     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++     // 2. performing jqUploader flash upload     if ($_FILES['Filedata']['name']) {       if (move_uploaded_file ($_FILES['Filedata']['tmp_name'], $uploadFile)) {         // delete the file         // @unlink ($uploadFile);         return $uploadFile;       }     } else {       if ($_FILES['Filedata']['error']) {         return $_FILES['Filedata']['error'];       }     }   } } // /////////////////// HELPER FUNCTIONS function myHtml($bodyHtml) {   ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jqUploader demo - Result</title> <link rel="stylesheet" type="text/css" media="screen" href="style.css"/> </head> <body> <?php echo $bodyHtml;   ?> </body> </html> <?php } ?>   Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136283 Share on other sites More sharing options...
BlueSkyIS Posted November 18, 2010 Share Posted November 18, 2010 you can't submit 2 forms at the same time. you'll need to combine them into one. remove these lines: Â Â </form> <form id="ContactForm" action=""> Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136284 Share on other sites More sharing options...
webguync Posted November 18, 2010 Author Share Posted November 18, 2010 yea, I have tried to combine the two, but neither works(the upload and the formation information submit) when I do that. Here is what the combined code looks like.  <form id="ContactForm" action="">       <fieldset>         <p>           <label>First Name</label>           <input id="FirstName" name="FirstName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span>         </p>         <p>           <label>Last Name</label>           <input id="LastName" name="LastName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span>         </p>         <p>           <label>User Name</label>           <input id="UserName" name="UserName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span>         </p>         <p>           <label>Password</label>           <input type="password" id="Password" name="Password" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span>         </p>         <p>           <label>Email</label>           <input id="email" name="email" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span>         </p>         <p>           <label>Zip Code</label>           <input id="Zip" name="Zip" class="inplaceError" maxlength="12" type="text" autocomplete="off"/>           <span class="error" style="display:none;"></span>         </p>         <p>           <label>Birthday (mm/dd/yyyy format)</label>           <input id="Birthday" name="Birthday" class="inplaceError" maxlength="12" type="text" autocomplete="off"/>           <span class="error" style="display:none;"></span>         </p>          <p>           <label>Security Question</label>           <input id="Security" name="Security" class="inplaceError" maxlength="255" type="text" autocomplete="off"/>           <span class="error" style="display:none;"></span>         </p>               <input id="newcontact" name="newcontact" type="hidden" value="1"></input>         <p class="submit">           <input id="send" type="button" value="Join"/>           <span id="loader" class="loader" style="display:none;"></span> <span id="success_message" class="success"></span>           <span id="success_message" class="fail"></span>                  </p>         <label for="FileUpload">Choose a file to upload:</label>     <input name="myfile" id="FileUpload" type="file" />         </fieldset>       </form>       <?php ini_set("display_errors","1"); ERROR_REPORTING(E_ALL); require_once("db.php"); /* Database Class */ require_once('utils/is_email.php'); /* Email Validation Script */ /* Handle Ajax Request */ if(isset($_POST['newcontact'])){ $contact = new Contact(); unset($contact); } else{ header('Location: /'); } /* Class Contact */ class Contact{ private $db; /* the database obj */ private $errors = array(); /* holds error messages */ private $num_errors; /* number of errors in submitted form */ public function __construct(){ $this->db = new DB(); if(isset($_POST['newcontact'])) $this->processNewMessage(); else header("Location: /"); } public function processNewMessage(){ $email = $_POST['email']; $FirstName = $_POST['FirstName']; $LastName = $_POST['LastName']; $UserName = $_POST['UserName']; $Password = $_POST['Password']; $Zip =  $_POST['Zip']; $Birthday = $_POST['Birthday']; $Security = $_POST['Security']; $FileUpload = $_POST['FileUpload']; /* Server Side Data Validation */ /* Email Validation */ if(!$email || mb_strlen($email = trim($email)) == 0) $this->setError('email','required field'); else{ if(!is_email($email)) $this->setError('email', 'invalid email'); else if(mb_strlen($email) > 120) $this->setError('email', 'too long! 120'); } /* FirstName Validation */ if(!$FirstName || mb_strlen($FirstName = trim($FirstName)) == 0) $this->setError('FirstName', 'required field'); else if(mb_strlen(trim($FirstName)) > 120) $this->setError('FirstName', 'too long! 120 characters'); /* LastName Validation */ if(!$LastName || mb_strlen($LastName = trim($LastName)) == 0) $this->setError('LastName', 'required field'); else if(mb_strlen(trim($LastName)) > 120) $this->setError('LastName', 'too long! 120 characters'); /* UserName Validation */ if(!$UserName || mb_strlen($UserName = trim($UserName)) == 0) $this->setError('UserName', 'required field'); else if(mb_strlen(trim($UserName)) > 120) $this->setError('UserName', 'too long! 120 characters'); /* Password Validation */ if(!$Password || mb_strlen($Password = trim($Password)) == 0) $this->setError('Password', 'required field'); else if(mb_strlen(trim($Password)) > 120) $this->setError('Password', 'too long! 120 characters'); /* zip code Validation */ if(!$Zip || mb_strlen($Zip = trim($Zip)) == 0) $this->setError('Zip', 'required field'); else if(mb_strlen(trim($Zip)) > 120) $this->setError('Zip', 'too long! 120 characters'); /* Message Validation */ $Birthday = trim($Birthday); if(!$Birthday || mb_strlen($Birthday = trim($Birthday)) == 0) $this->setError('Birthday','required field'); elseif(mb_strlen($Birthday) > 300) $this->setError('Birthday', 'too long! 300 characters'); /* Security Validation */ $Security = trim($Security); if(!$Security || mb_strlen($Security = trim($Security)) == 0) $this->setError('Security','required field'); elseif(mb_strlen($Security) > 300) $this->setError('Security', 'too long! 300 characters'); /* Photo Validation */ $FileUpload = trim($FileUpload); if(!$FileUpload || mb_strlen($FileUpload = trim($FileUpload)) == 0) $this->setError('FileUpload','required field'); elseif(mb_strlen($FileUpload) > 300) $this->setError('FileUpload', 'too long! 300 characters'); /* Errors exist */ if($this->countErrors() > 0){ $json = array( 'result' => -1, 'errors' => array( array('name' => 'email' ,'value' => $this->error_value('email')), array('name' => 'FirstName' ,'value' => $this->error_value('FirstName')), array('name' => 'LastName' ,'value' => $this->error_value('LastName')), array('name' => 'UserName' ,'value' => $this->error_value('UserName')), array('name' => 'Password' ,'value' => $this->error_value('Password')), array('name' => 'Zip'  ,'value' => $this->error_value('Zip')), array('name' => 'Birthday' ,'value' => $this->error_value('Birthday')), array('name' => 'Security' ,'value' => $this->error_value('Security')), array('name' => 'FileUpload' ,'value' => $this->error_value('FileUpload')), ) ); $encoded = json_encode($json); echo $encoded; unset($encoded); } /* No errors, insert in db*/ else{ if(($ret = $this->db->dbNewMessage($email, $FirstName, $LastName,$UserName, $Password, $Zip, $Birthday, $Security,$FileUpload)) > 0){ $json = array('result' => 1); if(SEND_EMAIL) $this->sendEmail($email,$name,$website,$message); } else $json = array('result' => -2); /* something went wrong in database insertion */ $encoded = json_encode($json); echo $encoded; unset($encoded); } } public function sendEmail($email,$name,$website,$message){ /* Just format the email text the way you want ... */ $message_body = "Hi, ".$name."(".$email." - ".$website.") sent you a message from yoursite.com\n" ."email: ".$email."\n" ."message: "."\n" .$message; $headers = "From: ".EMAIL_FROM_NAME." <".EMAIL_FROM_ADDR.">"; return mail(EMAIL_TO,MESSAGE_SUBJECT,$message_body,$headers); } public function setError($field, $errmsg){ $this->errors[$field] = $errmsg; $this->num_errors = count($this->errors); } public function error_value($field){ if(array_key_exists($field,$this->errors)) return $this->errors[$field]; else return ''; } public function countErrors(){ return $this->num_errors; } }; /*file upload code*/ $uploadDir = dirname(__FILE__) . '/files/'; $uploadFile = $uploadDir . basename($_FILES['Filedata']['name']); if ($_POST['submit'] != '') {   // 1. submitting the html form   if (!isset($_GET['jqUploader'])) {     // 1.a javascript off, we need to upload the file     if (move_uploaded_file ($_FILES[0]['tmp_name'], $uploadFile)) {       // delete the file       // @unlink ($uploadFile);       $html_body = '<h1>File successfully uploaded!</h1><pre>';       $html_body .= print_r($_FILES, true);       $html_body .= '</pre>';     } else {       $html_body = '<h1>File upload error!</h1>';       switch ($_FILES[0]['error']) {         case 1:           $html_body .= 'The file is bigger than this PHP installation allows';           break;         case 2:           $html_body .= 'The file is bigger than this form allows';           break;         case 3:           $html_body .= 'Only part of the file was uploaded';           break;         case 4:           $html_body .= 'No file was uploaded';           break;         default:           $html_body .= 'unknown errror';       }       $html_body .= 'File data received: <pre>';       $html_body .= print_r($_FILES, true);       $html_body .= '</pre>';     }     $html_body = '<h1>Full form</h1><pre>';     $html_body .= print_r($_POST, true);     $html_body .= '</pre>';   } else {     // 1.b javascript on, so the file has been uploaded and its filename is in the POST array     $html_body = '<h1>Form posted!</h1><p>Error:<pre>';     $html_body .= print_r($_POST, false);     $html_body .= '</pre>';   }   myHtml($html_body); } else {   if ($_GET['jqUploader'] == 1) {     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++     // 2. performing jqUploader flash upload     if ($_FILES['Filedata']['name']) {       if (move_uploaded_file ($_FILES['Filedata']['tmp_name'], $uploadFile)) {         // delete the file         // @unlink ($uploadFile);         return $uploadFile;       }     } else {       if ($_FILES['Filedata']['error']) {         return $_FILES['Filedata']['error'];       }     }   } } // /////////////////// HELPER FUNCTIONS function myHtml($bodyHtml) { ?> upload to database  <?php require_once("config.php"); /* Configuration File */ class DB{ private $link; public function __construct(){ $this->link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME); if (mysqli_connect_errno())   exit(); } public function __destruct() { mysqli_close($this->link); } public function dbNewMessage($email,$FirstName,$LastName,$UserName,$Password,$Zip,$Birthday,$Security){ $email = mysqli_real_escape_string($this->link,$email); $FirstName = mysqli_real_escape_string($this->link,$FirstName); $LastName = mysqli_real_escape_string($this->link,$LastName); $UserName = mysqli_real_escape_string($this->link,$UserName); $Password = mysqli_real_escape_string($this->link,md5($Password)); $Zip =  mysqli_real_escape_string($this->link,$Zip); $Birthday = mysqli_real_escape_string($this->link,$Birthday); $Security = mysqli_real_escape_string($this->link,$Security); $FileUpload = mysqli_real_escape_string($this->link,$FileUpload); mysqli_autocommit($this->link,FALSE); $query = "INSERT INTO Profile(pk_contact,email,FirstName,LastName,UserName,Password,Zip,Birthday,Security,FileUpload)  VALUES('NULL','$email','$FirstName','$LastName','$UserName','$Password','$Zip','$Birthday','$Security','$FileUpload')"; mysqli_query($this->link,$query); mail("webguync@gmail.com","ajax debug","$sql\n\n mysqli_query = $query"); if(mysqli_errno($this->link)) return -1; else{ mysqli_commit($this->link); return 1; } } }; ?> JQuery to handle the submit and return a result.  $(document).ready(function() { contact.initEventHandlers(); }); var contact = { initEventHandlers : function() { /* clicking the submit form */ $('#send').bind('click',function(event){ $('#loader').show(); setTimeout('contact.ContactFormSubmit()',500); }); /* remove messages when user wants to correct (focus on the input) */ $('.inplaceError',$('#ContactForm')).bind('focus',function(){ var $this = $(this); var $error_elem = $this.next(); if($error_elem.length) $error_elem.fadeOut(function(){$(this).empty()}); $('#success_message').empty(); }); /* user presses enter - submits form */ $('#ContactForm input,#ContactForm textarea').keypress(function (e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { $("#send").click(); return false; } else return true; }); }, ContactFormSubmit : function() { $.ajax({  type : 'POST',  url : 'php/contact.php?ts='+new Date().getTime(),  dataType : 'json',  data : $('#ContactForm').serialize(),  success : function(data,textStatus){  //hide the ajax loader  $('#loader').hide();  //alert("The Bug Is Somewhere Before ME!")                alert(data);  if(data.result == '1'){     //show success message  $('#success_message').empty().html('Message sent');  //reset all form fields  $('#ContactForm')[0].reset();  //envelope animation  $('#envelope').stop().show().animate({'marginTop':'-175px','marginLeft':'-246px','width':'492px','height':'350px','opacity':'0'},function(){    $(this).css({'width':'246px','height':'175px','margin-left':'-123px','margin-top':'-88px','opacity':'1','display':'none'});  });  }  else if(data.result == '-1'){  for(var i=0; i < data.errors.length; ++i ){    if(data.errors[i].value!='')      $("#"+data.errors[i].name).next().html('<span>'+data.errors[i].value+'</span>').fadeIn();  $('#success_message').empty().html('Form not complete!');  }  }   },  error : function(data,textStatus){} }); } };   Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136290 Share on other sites More sharing options...
webguync Posted November 18, 2010 Author Share Posted November 18, 2010 I think I want to just focus on getting the image upload moved over to the MySQL DB for now. What I currently have isn't working :-(  I have my DB table set us as follow:  CREATE TABLE IF NOT EXISTS `Profile_Photos` (  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,  `Photo` text NOT NULL,  `added_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,  PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;  The File upload code is this. The uploading to the file directory works fine, so I just need to be able to insert the path to the image in my Profile_Photos table.  <?php ini_set("display_errors","1"); ERROR_REPORTING(E_ALL); session_start(); $db_user = "user_name"; $db_pass = "DBPass"; $db = "DBName"; mysql_connect('localhost',$db_user,$db_pass); mysql_select_db($db); $uploadDir = dirname(__FILE__) . '/files/'; $uploadFile = $uploadDir . basename($_FILES['Filedata']['name']); if ($_POST['submit'] != '') {   // 1. submitting the html form   if (!isset($_GET['jqUploader'])) {     // 1.a javascript off, we need to upload the file     if (move_uploaded_file ($_FILES[0]['tmp_name'], $uploadFile)) {       // delete the file       // @unlink ($uploadFile);       $html_body = '<h1>File successfully uploaded!</h1><pre>';       $html_body .= print_r($_FILES, true);       $html_body .= '</pre>';     } else {       $html_body = '<h1>File upload error!</h1>';       switch ($_FILES[0]['error']) {         case 1:           $html_body .= 'The file is bigger than this PHP installation allows';           break;         case 2:           $html_body .= 'The file is bigger than this form allows';           break;         case 3:           $html_body .= 'Only part of the file was uploaded';           break;         case 4:           $html_body .= 'No file was uploaded';           break;         default:           $html_body .= 'unknown errror';       }       $html_body .= 'File data received: <pre>';       $html_body .= print_r($_FILES, true);       $html_body .= '</pre>';     }     $html_body = '<h1>Full form</h1><pre>';     $html_body .= print_r($_POST, true);     $html_body .= '</pre>';   } else {     // 1.b javascript on, so the file has been uploaded and its filename is in the POST array     $html_body = '<h1>Form posted!</h1><p>Error:<pre>';     $html_body .= print_r($_POST, false);     $html_body .= '</pre>';   }   myHtml($html_body); } else {   if ($_GET['jqUploader'] == 1) {     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++     // 2. performing jqUploader flash upload     if ($_FILES['Filedata']['name']) {       if (move_uploaded_file ($_FILES['Filedata']['tmp_name'], $uploadFile)) { mysql_query("insert into Profile_Photos (filename) values ('{$uploadFile}')");         // delete the file         // @unlink ($uploadFile);         return $uploadFile;       }     } else {       if ($_FILES['Filedata']['error']) {         return $_FILES['Filedata']['error'];       }     }   } } // /////////////////// HELPER FUNCTIONS function myHtml($bodyHtml) {   ?> Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136366 Share on other sites More sharing options...
webguync Posted November 19, 2010 Author Share Posted November 19, 2010 can anyone assist with this? I need to get this figured out. Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136644 Share on other sites More sharing options...
ManiacDan Posted November 19, 2010 Share Posted November 19, 2010 What, exactly, is the problem? I see a properly formatted INSERT statement. Have you done any debugging on your own? Have you echoed the query or checked the mysql error message? Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136657 Share on other sites More sharing options...
webguync Posted November 19, 2010 Author Share Posted November 19, 2010 I added some debugging and error reporting and noticed these warnings, perhaps this is the problem. Â Notice: Undefined index: Filedata inflash_upload.php on line 24 Notice: Undefined index: submit in flash_upload.php on line 26 Notice: Undefined index: jqUploader in flash_upload.php on line 70 Â that would be these lines $uploadFile = $uploadDir . basename($_FILES['Filedata']['name']); if ($_POST['submit'] != '') if ($_GET['jqUploader'] == 1) { Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136673 Share on other sites More sharing options...
ManiacDan Posted November 19, 2010 Share Posted November 19, 2010 The first error means you've mistyped your form field name. Print_r $_FILES to see what it should be.  The second means that the form hasn't been submitted, or you've mistyped your submit button name.  The third means that the URL doesn't contain the variables you think it does.   Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136679 Share on other sites More sharing options...
webguync Posted November 19, 2010 Author Share Posted November 19, 2010 here is the form code <form enctype="multipart/form-data" action="flash_upload.php" method="POST" class="a_form"> Â Â <fieldset> Â Â <legend>Upload your profile picture</legend> Â Â <ol> Â Â Â <li id="example3"> Â Â Â Â <label for="FileUpload">Choose a file to upload:</label> Â Â Â Â <input name="myfile" id="FileUpload"Â type="file" /> Â Â Â </li> Â Â </ol> Â Â </fieldset> Â Â Â </form> Â print_r just gave me an empty array Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136686 Share on other sites More sharing options...
ManiacDan Posted November 19, 2010 Share Posted November 19, 2010 print_r just gave me an empty arrayThere's no submit button on that form. You're not submitting anything, leaving your $_POST and $_FILES arrays empty. -Dan Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136720 Share on other sites More sharing options...
jdavidbakr Posted November 19, 2010 Share Posted November 19, 2010 Are you sure this block of code is being executed:      // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++     // 2. performing jqUploader flash upload     if ($_FILES['Filedata']['name']) {       if (move_uploaded_file ($_FILES['Filedata']['tmp_name'], $uploadFile)) {         mysql_query("insert into Profile_Photos (filename) values ('{$uploadFile}')");         // delete the file         // @unlink ($uploadFile);         return $uploadFile;       }  try echo mysql_error() immediately after the query. You might also try pulling the query out into a variable and echoing that as well, just to make sure the query is what you expect. I.e.  if ($_FILES['Filedata']['name']) {       if (move_uploaded_file ($_FILES['Filedata']['tmp_name'], $uploadFile)) {         $statement = "insert into Profile_Photos (filename) values ('{$uploadFile}')";         echo "<P>".$statement;         mysql_query($statement);         echo "<P>".mysql_error();         // delete the file         // @unlink ($uploadFile);         return $uploadFile;       } Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136727 Share on other sites More sharing options...
webguync Posted November 19, 2010 Author Share Posted November 19, 2010 ok, I added the error handling and the submit button. When I submit I get these errors and result from print_r  Connected successfully Notice: Undefined index: Filedata in flash_upload.php on line 24 Notice: Undefined offset: 0 in /new_site/flash_upload.php on line 31 Notice: Undefined offset: 0 in /new_site/flash_upload.php on line 40 Array (   [undefined] => imageuploaded.png   [submit] => Send ) the lines in question are $uploadFile = $uploadDir . basename($_FILES['Filedata']['name']); if (move_uploaded_file ($_FILES[0]['tmp_name'], $uploadFile)) { switch ($_FILES[0]['error']) {  [/code] Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136735 Share on other sites More sharing options...
jdavidbakr Posted November 19, 2010 Share Posted November 19, 2010 You've got a number of versions of the form above - what does the form html actually look like right now? Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136740 Share on other sites More sharing options...
webguync Posted November 19, 2010 Author Share Posted November 19, 2010 the file upload form looks like this... Â Â <form enctype="multipart/form-data" action="flash_upload.php" method="POST" class="a_form"> Â Â <fieldset> Â Â <legend>Upload your profile picture</legend> Â Â <ol> Â Â Â <li id="example3"> Â Â Â Â <label for="FileUpload">Choose a file to upload:</label> Â Â Â Â <input name="myfile" id="FileUpload"Â type="file" /> Â Â Â </li> Â Â </ol> Â Â </fieldset> Â Â <input type="submit" name="submit" value="Send" /> Â </form> Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136750 Share on other sites More sharing options...
jdavidbakr Posted November 19, 2010 Share Posted November 19, 2010 The name of your file is "myfile" not "Filedata" - change  $uploadFile = $uploadDir . basename($_FILES['Filedata']['name']);  to  $uploadFile = $uploadDir . basename($_FILES['myfile']['name']);  as well as any other instances of "$_FILES['Filedata']" to "$_FILES['myfile']" Quote Link to comment https://forums.phpfreaks.com/topic/218782-help-with-uploading-a-picture-to-mysql-db/#findComment-1136754 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.