Upload File with PHP and Save Path to SQL

upload file with php and save path to sql

To upload a file you need at least a HTML POST form with multipart/form-data encoding. Therein you put an input type="file" field to browse the file and a submit button to submit the form.

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>

In the upload.php the uploaded file is accesible by $_FILES with the field name as key.

$file = $_FILES['file'];

You can get its name as follows:

$name = $file['name'];

You need to move it to a permanent location using move_uploaded_file(), else it will get lost:

$path = "/uploads/" . basename($name);
if (move_uploaded_file($file['tmp_name'], $path)) {
// Move succeed.
} else {
// Move failed. Possible duplicate?
}

You can store the path in database the usual way:

$sql = "INSERT INTO file (path) VALUES ('" . mysqli_real_escape_string($path) . "')";
// ...

How to store file path using PHP file upload

You should try something like this :

<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="test"; // Database name
//$tbl_name="members"; // Table name
$con=mysql_connect("localhost","root","");
if(! $con)
{
die('Connection Failed'.mysql_error());
}
mysql_select_db("test123",$con);

if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
$file_path=$_FILES['files']['path'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}

//$desired_dir=$options['upload_dir']."user_data";
$desired_dir="user_data";
if(empty($errors)==true)
{
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 755); // Create directory if it does not exist
}

$file_path_name = "$desired_dir/".$file_name;

if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}

$query="INSERT into upload(`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`,`FILE_PATH`) VALUES('$file_name','$file_size','$file_type', '$file_path_name'); ";
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>

upload file and save the path to mysql in codeigniter

try:
$file1=($config['upload_path'].$_FILES['file1']['name']);

for each of the files you upload.

properly save file upload contents to MySQL DB to retrieve as a link

"@Fred, yes it was a directory issue. Upon fixing this issue, I was able to successfully link the the page and view it. If you summarize your two suggestions as an answer, I will mark your response as the correct answer. Thank you!"

As I stated in comments:

The duplicate entries are caused by $conn->query($sql); if($conn->query($sql))

where there were two instances of query() being used.

You can just use the conditional statement and omit $conn->query($sql);.

For the path issue, this was also stated in comments that the folder's path wasn't properly indexed.


Footnotes:

You're presently open to an SQL injection. Best you use a prepared statement.

  • https://en.wikipedia.org/wiki/Prepared_statement

Using PHP to upload file and add the path to MySQL database

First you should use print_r($_FILES) to debug, and see what it contains. :

your uploads.php would look like:

//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);

//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];

//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO picture (Filename,Description)
VALUES ('$Filename', '$Description')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}

?>

EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php

file is uploaded into folder but path is not stored into database

i execute the code.
The Problem is in your Schema

Data truncation: Data too long for column 'type' at row 1

Try to Run Following Than Perform Insertions It Would be insert

ALTER TABLE `users` CHANGE `size` `size` INT(30) NOT NULL;

Saving Image Path in PHP and SQL

The best practice is to save only directory and product name in the database and upload file to folder for later retrieval. So kudos for using good practices.

As you've guessed, the problem is that your app is not recognizing the variable :

$imag1_prod=$_FILES["imag1_prod"][ "name" ];

Because you are renaming it here :

move_uploaded_file($_FILES["imag1_prod"][" tmp_name "]

The other issue here is that you are forgetting to store the filename as well as the directory.

Try this :

if(isset($_FILES['imag1_prod']['name'])) {

//post variables
$ident_prod = mysqli_real_escape_string($con,(strip_tags($_POST["ident_prod"],ENT_QUOTES)));
$ident_cate = mysqli_real_escape_string($con,(strip_tags($_POST["ident_cate"],ENT_QUOTES)));
$nombr_prod = mysqli_real_escape_string($con,(strip_tags($_POST["nombr_prod"],ENT_QUOTES)));
$desco_prod = mysqli_real_escape_string($con,(strip_tags($_POST["desco_prod"],ENT_QUOTES)));
$desla_prod = mysqli_real_escape_string($con,(strip_tags($_POST["desla_prod"],ENT_QUOTES)));
$preci_prod = mysqli_real_escape_string($con,(strip_tags($_POST["preci_prod"],ENT_QUOTES)));
$pesoo_prod = mysqli_real_escape_string($con,(strip_tags($_POST["pesoo_prod"],ENT_QUOTES)));
$taman_prod = mysqli_real_escape_string($con,(strip_tags($_POST["taman_prod"],ENT_QUOTES)));
$stock_prod = mysqli_real_escape_string($con,(strip_tags($_POST["stock_prod"],ENT_QUOTES)));
$estad_prod = mysqli_real_escape_string($con,(strip_tags($_POST["estad_prod"],ENT_QUOTES)));

//get filename
$filename = $_FILES['imag1_prod']['name'];

//rename file
$temp = explode(".", $_FILES["imag1_prod"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);

//set path
$target_dir = "../imagen/productos/";

//upload files in folder
move_uploaded_file($_FILES['imag1_prod']['tmp_name'], "$target_dir/$newfilename");

//rename file with directory name
$filenamedirectory = $target_dir/$newfilename;

$statu_prod = 1;

// Registrar en la Base de Datos
$sql = "INSERT INTO tabma_prod(ident_prod, ident_cate, nombr_prod, desco_prod, desla_prod, preci_prod, pesoo_prod, taman_prod, stock_prod, estad_prod, imag1_prod, statu_prod)
VALUES ('$ident_prod',(SELECT ident_cate FROM tabma_cate WHERE ident_cate = '$ident_cate'),'$nombr_prod','$desco_prod','$desla_prod','$preci_prod','$pesoo_prod','$taman_prod','$stock_prod','$estad_prod','$filenamedirectory','$statu_prod') ";
}

Also make sure you use prepared statement to avoid SQL injections when performing database operations.



Related Topics



Leave a reply



Submit