Jump to content

Data Insert Form With Image/pdf Upload


claw2504

Recommended Posts

I have made a simple html form that uses an insert.php to input data in to my mysql DB (that is used for my search).At the moment the form only consists of text fields, however I need to updload an image and a PDF to the record all at the same time. I basicly want to upload the two items to the server and simply store the file path in the database....... problem is I have no idea how to do this short of manualy uploading the two and manualy typing the filepaths into the mysql DB. Can someone please help me out?!Code so far (stripped down to basic's):-[uHTML ]Form[/u]

<form action="insert.php" method="post">Project Number: <input type="text" name="projectnumber" />Property: <input type="text" name="property" />Address: <input type="text" name="address" />City: <input type="text" name="city" />Post Code: <input type="text" name="postcode" /><input type="submit" /></form>

insert.php

$sql="INSERT INTO database_name (projectnumber, property, address, city, postcode)VALUES('$_POST[projectnumber]','$_POST[property]','$_POST[address]','$_POST[city]','$_POST[postcode]')";if (!mysql_query($sql,$con))  {  die('Error: ' . mysql_error());  }echo "1 record added";mysql_close($con)?>

This needs to be upload at the same time as the new record is inserted so that it gets matched up witht the right property.Would really appreciate help on this as I have scoured the net for hours and short of purchasing a program (which doesn't teach jack) can figure it out.Thanks again, in advance.

Link to comment
Share on other sites

Check here:http://www.php.net/manual/en/features.file-upload.phpOnce you understand how file uploads work through a form, you can use this function to handle the uploaded files:

function handle_file_upload($options){  $input = !empty($options['input']) ? $options['input'] : trigger_error('handle_file_upload: No input name specified', E_USER_ERROR);  $dest = !empty($options['dest_dir']) ? $options['dest_dir'] : trigger_error('handle_file_upload: No destination directory specified', E_USER_ERROR);  $dest_fname = !empty($options['dest_fname']) ? $options['dest_fname'] : '';  $overwrite = !empty($options['overwrite']) ? $options['overwrite'] : false;  $mode = !empty($options['mode']) ? $options['mode'] : false;  $allowed_ext = isset($options['allowed_ext']) && is_array($options['allowed_ext']) ? $options['allowed_ext'] : false;  if (!is_dir($dest))	trigger_error('handle_file_upload: Destination directory does not exist', E_USER_ERROR);  if (!isset($_FILES[$input]))	trigger_error('handle_file_upload: The input file was not found', E_USER_ERROR);  if ($_FILES[$input]['error'] > 0)  {	switch ($_FILES[$input]['error'])	{	  case 1:	  case 2; return array('success' => false, 'error' => 'The uploaded file was too large.');	  case 3: return array('success' => false, 'error' => 'The uploaded file was only partially received.');	  case 4: return array('success' => false, 'error' => 'No file was uploaded.');	  case 6: return array('success' => false, 'error' => 'Missing temporary folder.');	  case 7: return array('success' => false, 'error' => 'Failed to write file to disk.');	  case 8: return array('success' => false, 'error' => 'Invalid extension.');	}  }    if ($allowed_ext != false && !in_array(strtolower(array_pop(explode('.', $_FILES[$input]['name']))), $allowed_ext))	return array('success' => false, 'error' => 'That file type was not allowed.');  if ($dest_fname != '')	$_FILES[$input]['name'] = $dest_fname;  $_FILES[$input]['name'] = strtolower(basename($_FILES[$input]['name']));  if (!$overwrite)  {	$fname = $_FILES[$input]['name'];	if (file_exists($dest . DIRECTORY_SEPARATOR . $fname))	{	  $chunks = explode('.', $fname);	  $ext = array_pop($chunks);	  $fname = implode('.', $chunks);	  $nr = 1;	  while (file_exists($dest . DIRECTORY_SEPARATOR . $fname . '.' . $ext))		$fname = $fname . '.' . $nr++;	  $_FILES[$input]['name'] = $fname . '.' . $ext;	}  }  $target = $dest . DIRECTORY_SEPARATOR . $_FILES[$input]['name'];  if (!move_uploaded_file($_FILES[$input]['tmp_name'], $target))	return array('success' => false, 'error' => 'The uploaded file could not be moved.');  if ($mode !== false)	chmod($target, $mode);  return array('success' => true, 'name' => $_FILES[$input]['name']);}

e.g.:

$file = handle_file_upload(array(  'input' => 'file_input_name',  'dest_dir' => '/path/to/save',  'overwrite' => false,  'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png')));if ($file['success']){  $filename = $file['name'];}else{  echo $file['error'];}

Link to comment
Share on other sites

Thanks. I understand how to make the script to upload a file to the database.However, i am unsure how to upload a files to the server,and save the file path to the database (I have found examples for this alone) along with text and ensure it's all saved in the database for the new record.

Link to comment
Share on other sites

All of the form data gets submitted at once, so if your form includes your file upload fields then those will be uploaded along with the rest of the data. Before you insert the record into the database you can process the uploaded files so that you know what filename to add to the record. The function I posted will process the files.

Link to comment
Share on other sites

Thank you. Just so I get this right, the best way to do this would be to upload the files and have a script that displays the filepath after it sucessfully uploads then use a standard form that inserts all the information in to the correct fields.Thanks again mate! I do believe you have solved my problem!

Link to comment
Share on other sites

I was more thinking that you would only use 1 form to both upload the files and submit whatever other information is going into the other fields, that's the normal way of doing it. e.g.:

<form action="insert.php" method="post" enctype="multipart/form-data">Project Number: <input type="text" name="projectnumber" /><br />Property: <input type="text" name="property" /><br />Address: <input type="text" name="address" /><br />City: <input type="text" name="city" /><br />Post Code: <input type="text" name="postcode" /><br />Image: <input type="file" name="image" /><input type="submit" /></form>

Link to comment
Share on other sites

It's not that hard, the first step is just to create your one form with all of the fields, so whatever fields you want to capture plus the image upload fields. Once you get the form looking right then we can worry about the PHP code, but first get your form set up with the fields you want and then post that. Or, if someone else wants to charge you to make that then that's fine too. I don't have a lot of free time though, but I'm willing to help here.

Link to comment
Share on other sites

OK, thanks for your reply. Here is the form I have made, with all the fields I require.

<form action="insert.php" method="post" enctype="multipart/form-data">Project Number: <input type="text" name="projectnumber" /><br />Property Code: <input type="text" name="propertycode" /><br />Property: <input type="text" name="property" /><br />Address: <input type="text" name="address" /><br />City: <input type="text" name="city" /><br />Post Code: <input type="text" name="postcode" /><br />Last Inspection: <input type="text" name="lastinspection" /><br />Image: <input type="file" name="image" /><br />PDF Report: <input type="file" name="pdfreport" /><br /><input type="submit" /></form>

Link to comment
Share on other sites

For the first several fields, you can just get those directly from $_POST:

$proj_num = $_POST['projectnumber'];$prop_code = $_POST['propertycode'];...

For the files, to process both of those files you could use this, just change the destination directory to wherever you want to save them:

$image = $pdf = '';$file = handle_file_upload(array(  'input' => 'image',  'dest_dir' => '/path/to/save',  'overwrite' => false,  'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png')));if ($file['success']){  $image = $file['name'];}$file = handle_file_upload(array(  'input' => 'pdfreport',  'dest_dir' => '/path/to/save',  'overwrite' => false,  'allowed_ext' => array('pdf')));if ($file['success']){  $pdf = $file['name'];}

So, without any validation or error checking, your basic code would look like this:

<?php$proj_num = $_POST['projectnumber'];$prop_code = $_POST['propertycode'];// other fields$image = $pdf = '';$file = handle_file_upload(array(  'input' => 'image',  'dest_dir' => '/path/to/save',  'overwrite' => false,  'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png')));if ($file['success']){  $image = $file['name'];}$file = handle_file_upload(array(  'input' => 'pdfreport',  'dest_dir' => '/path/to/save',  'overwrite' => false,  'allowed_ext' => array('pdf')));if ($file['success']){  $pdf = $file['name'];}$sql = 'INSERT INTO table_name (projectnumber, propertycode, image, pdf) VALUES (';$sql .= "'" . mysql_real_escape_string($proj_num) . "',";$sql .= "'" . mysql_real_escape_string($prop_code) . "',";$sql .= "'" . mysql_real_escape_string($image) . "',";$sql .= "'" . mysql_real_escape_string($pdf) . "'";$sql .= ')';mysql_query($sql) or exit(mysql_error());?>

You can add the other fields you need, plus any validation you want to do to make sure required things are filled out, but that's the general idea.

Link to comment
Share on other sites

Hey, heres the code all put together:-

<?php$con = mysql_connect("localhost","root","");if (!$con)  {  die('Could not connect: ' . mysql_error());  }mysql_select_db("harvey_pub_co", $con);$report_number = $_POST['report_number'];$property_code = $_POST['property_code'];$property = $_POST['property'];$address = $_POST['address'];$city = $_POST['city'];$post_code = $_POST['post_code'];$last_inspection = $_POST['last_inspection'];$image = $pdf = '';$file = handle_file_upload(array(  'input' => 'image',  'dest_dir' => 'www/asbestos_register/harvey_pub_company/properties/photo/',  'overwrite' => false,  'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png')));if ($file['success']){  $image = $file['name'];}$file = handle_file_upload(array(  'input' => 'pdfreport',  'dest_dir' => 'www/asbestos_register/harvey_pub_company/properties/register/',  'overwrite' => false,  'allowed_ext' => array('pdf')));if ($file['success']){  $pdf = $file['name'];}$sql = 'INSERT INTO asbestos_register (report_number, property_code, property, address, city, post_code, last_inspection, image, pdf) VALUES (';$sql .= "'" . mysql_real_escape_string($report_number) . "',";$sql .= "'" . mysql_real_escape_string($property_code) . "',";$sql .= "'" . mysql_real_escape_string($property) . "',";$sql .= "'" . mysql_real_escape_string($address) . "',";$sql .= "'" . mysql_real_escape_string($city) . "',";$sql .= "'" . mysql_real_escape_string($post_code) . "',";$sql .= "'" . mysql_real_escape_string($last_inspection) . "',";$sql .= "'" . mysql_real_escape_string($image) . "',";$sql .= "'" . mysql_real_escape_string($pdf) . "'";$sql .= ')';mysql_query($sql) or exit(mysql_error());?>

When I try to submit the form, to insert the data I get the following error:-Fatal error: Call to undefined function handle_file_upload() in C:\wamp\www\Asbestos_Register\administration\harvey_pub_company\insert.php on line 21Can you please help me out?

Link to comment
Share on other sites

I posted the function in post 2, you can either paste the function definition into that same page, or put the function in another PHP file and then include the file on that page. It's generally more maintainable if you keep your custom functions in an include file that you can include on any page where you want to use them. In general, it doesn't matter where in the code you define the function, if you want to just paste the function into that code you can paste it at the end to keep it separate from the rest of the logic on the page.

Link to comment
Share on other sites

Sorry, my fault being special!! Ive got the script working, only problem I have now is that once it uploads it only stores the name of the file as opposed to filepath and file name so the links do not work. Can you please help me in changing the script so that it stores the full filepath and filename.Thanks again for your help

Link to comment
Share on other sites

I normally just store the filename and add the path when I print it out, that way if I move all the files I don't need to change the database, just the script that prints them. If you want to add the HTTP path you can prepend it to the filename here:$image = $file['name'];...$pdf = $file['name'];

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...