Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store files in MySQL database from HTML form

I've got the following HTML form. As you can see it's saving a file.

<form enctype="multipart/form-data" action="welcome.php" method="post
"onsubmit="return validateFormOnSubmit(this)"> 
 <b>Name</b><br/> <input type="text" name="fname" /> 
 <br/>
 <b>Description</b><br/> <TEXTAREA NAME="description" COLS=40
 ROWS=6></TEXTAREA><br/><br/> <input type="hidden" name="MAX_FILE_SIZE" value="100000"/> 

<b>Upload Picture</b><br/> <input name="uploadedfile" type="file" /><br /> 
 <b>Latitude</b><br/><INPUT name="lat" id ="lat" /><br/> 
 <b>Longitude</b><br/><INPUT     name="lng" id ="lng" /><br/> <input type="submit" />

This file is being processed like so...

 $target_path = "uploads/";

 $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

The rest of the information is being stored in a SQL database. I'd like to store the file uploaded in that database. How would I go about doing this via the php file the information get's sent to? I'm inserting it like..

   $query = "INSERT INTO <TABLE> (name, message, lat, lng, type)VALUES ('".$title."', '".$des."', '".$lati."', '".$long."', '".$type."')";
   $q=mysql_query($query) or die(mysql_error());
like image 310
Skizit Avatar asked Jan 25 '26 11:01

Skizit


2 Answers

If you definitely want to insert your HTML file in your MySQL DB, there are two ways:

  1. Use the BLOB type to store the file.

  2. Convert your file into a string, as it is HTML, and store it in a TEXT field.

However, my recommendation would be to store files on the server filesystem, and not in the database.

like image 74
Guillaume Lebourgeois Avatar answered Jan 28 '26 01:01

Guillaume Lebourgeois


You can do this in tow ways.

  1. Copying the file into filesystem and saving its path in database

  2. Storing the file as binary data in database.

    $data = file_get_contents($_FILES['photo']['tmp_name']);
    $data = mysql_real_escape_string($data);
    

and then save data in a field (you need to create that field as blob)

like image 26
ahmetunal Avatar answered Jan 28 '26 00:01

ahmetunal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!