I'd like to include in my MySQL table a path to an image. The image path gets into the table by inserting the value of a "file" textfield (one of those Browse kind of deals). So the value that gets entered is something like: image001.jpg. But I can't seem to use that value to put an image into a html page. if it goes into the table fine, why can't I get it out?
I upload an image but I don't know where it's gone. Because there's no value entered in image field when I checked it through PhpMyadmin.
Table schema
CREATE TABLE employee_details
(
emp_image varchar(255),
employee_name varchar(50),
employee_address varchar(50),
employee_designation varchar(50),
employee_salary int(),
);
Query
$sql="
INSERT INTO employee_detail(
emp_image,
employee_name,
employee_address,
employee_contact,
employee_designation,
employee_salary
)
VALUES(
'$_POST[emp_image]',
'$_POST[employee_name]',
'$_POST[employee_address]',
'$_POST[employee_contact]',
'$_POST[employee_designation]',
'$_POST[employee_salary]'
)";
On your comment you ask how to upload and store the data to mysql. So here it is:
To get the file, you should have a script in your html like this:
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Now, on POST, your PHP file should look like this but please take note that you have to check if the file exists on your POST:
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
Since the "Stored in:" part is just the temporary path, you should move to your 'real' image path using move_uploaded_file().
Let say the real/default path for your images is in:
$image_dir= '/images/';
You just have to move the file using this:
move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $image_dir. $_FILES['uploaded_file']['name']);
And your full path to the image would be
$image = $final_save_dir . $_FILES['uploaded_file']['name'];
There are several ways to store the path to your database:
1st: Is to store just the filename and concatenate the path of the image in PHP using $_SERVER['DOCUMENT_ROOT'] and your default image path like:
$sql="insert into employee_detail( emp_image, employee_name, employee_address,
employee_contact, employee_designation, employee_salary)
values( '$image', '$_POST[employee_name]', '$_POST[employee_address]', '$_POST[employee_contact]',
'$_POST[employee_designation]','$_POST[employee_salary]')";
2nd: Is to store the full path like:
$sql="insert into employee_detail( emp_image, employee_name, employee_address,
employee_contact, employee_designation, employee_salary)
values( '".$_SERVER['DOCUMENT_ROOT']."\\images\\".$image."', '$_POST[employee_name]', '$_POST[employee_address]', '$_POST[employee_contact]',
'$_POST[employee_designation]','$_POST[employee_salary]')";
What I recommend is this approach wherein you will input the partial path (without the root dir) so that later you don't have a problem on deploying it:
$sql="insert into employee_detail( emp_image, employee_name, employee_address,
employee_contact, employee_designation, employee_salary)
values( 'images\\".$image."', '$_POST[employee_name]', '$_POST[employee_address]', '$_POST[employee_contact]',
'$_POST[employee_designation]','$_POST[employee_salary]')";
And make sure that the images are successfully upload to that default image dir/path.
UPDATE
I also recommend that you use mysqli_* or PDO and use prepare() method /function to prevent sql injection.
If you upload an image, it is saved in the temporary path at first. You'll have to move it to your final directory, otherwise it'll be gone after script execution. What basically happens is this:
If you have a form with some form fields (text, checkbox, textarea, whatever), AND a file field (<input type="file" name="uploaded_file" />), all 'normal' fields will be accessible with the $_POST array. The file(s) however will be accessible in the $_FILES array (see also the man page about file uploads).
Now when you receive the POST request, the uploaded files are stored in your temporary directory. If you don't do anything, it'll be deleted again after script execution. So you'd need to call the move_uploaded_file() function. Example:
$final_save_dir = '/path/to/images/dir/';
move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $final_save_dir . $_FILES['uploaded_file']['name']);
And your full path to the image would be
$image_full_path = $final_save_dir . $_FILES['uploaded_file']['name'];
This path can be saved in your database:
$sql="
INSERT INTO employee_detail(
emp_image,
...
)
VALUES(
'$image_full_path',
...
)";
IMPORTANT: please take note on #brewal's comment. Your script is VERY unsafe like this.
Related
I have a already functioning form that INSERT data into a db, i also have 4x file inputs for images, the form then adds all data, uplaods images and renames images to match the next ID and adds a random end to the filename.
this all works as intented
but i now need the filename(s) to be added to the database, sometimes the form will have 1x imaghe sometimes 4x images but im not sure how to store the filenames in the db from the below code. can anyone help? i assume the array needs to be broken down to individual filenames but not sure how to do it.
<?php
if(isset($_POST['submit'])){
// Variables for date&Time logs
$dateLog = date("y-m-d"); // DATE OF ADDITION
$timeLog = date("H:i:s", time() - 3600); // TIME OF ADDITION
// INSERT QUERY
$sql="INSERT INTO $table1 (firstname, lastname, companyname, phone, email, name, make, serial, catagory, price, location, description, sold, operational, year, clear, rip, version, service, dock, loading, available, extras, dateadded, featured)
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[companyname]','$dateLog','No')";
$query = mysql_query($sql) or die("Cannot query the database.<br>" . mysql_error());
// start of image upload
$insert_id = mysql_insert_id() or die("Unable to get insert id for image name.<br>" . mysql_error());
extract($_POST);
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists("../images/listings/".$txtGalleryName."/".$file_name))
{
$filename=basename($file_name,$ext);
$newFileName=$insert_id."_".mt_rand(1, 99999).".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"../images/listings/".$txtGalleryName."/".$newFileName);
}
else
{
$filename=basename($file_name,$ext);
$newFileName=$filename.mt_rand(1, 99999).".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"../images/listings/".$txtGalleryName."/".$newFileName);
}
}
else
{
array_push($error,"$file_name, ");
}
}
// end of image upload
echo '<p>This item was added successfully</p>';
}
?>
and my form;
1: Upload : <input type="file" name="files[]"/><br />
2: Upload : <input type="file" name="files[]"/><br />
3: Upload : <input type="file" name="files[]"/><br />
4: Upload : <input type="file" name="files[]"/><br />
appreciate any help :)
you can use $rename_var = rand('111111','999999'); and prepend it before the file name like $new_changed_name = $rename_var.$_FILES['files']['name']; and then use this name while saving the file in folder like so .. move_uploaded_file('tmp_name','path/'.$new_changed_name);
and insert this $new_changed_name new name into database.
I have a booking table which contain file_name and file_path, I need to upload a picture into the user row based on the noic, after I select a picture and click the upload button, it show upload success, but in the database doesn't have the picture and picture name.
$target = "upload/";
$target = $target . basename( $_FILES['file']['name']);
//This gets all the other information from the form
$file=basename( $_FILES['file']['name']);
$filename=$_POST['file_name'];
//Writes the file to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
//Writes the information to the database
mysql_query("UPDATE INTO booking (file_path,file_name)
VALUES ('$file', '$filename') WHERE noic = '$_SESSION[noic]'") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
<form enctype="multipart/form-data" action="userstatus.php" method="POST">
<p> File Name :
<input style="background:grey;" type="text" name="file_name" value="" >
</p>
<p>
<input type="file" name="file" >
</p>
<p>
<input type="submit" name="submit" value="Upload file" style="background:grey;">
</p>
</form>
Your MySQL query is incorrect, it should be UPDATE SET... MySQL Insert statement does not support the WHERE clause so your query will fail if you directly replace UPDATE with INSERT, make the following changes,
//Writes the information to the database
mysql_query("UPDATE booking SET file_path='$file',
file_name='$filename' WHERE noic = '$_SESSION[noic]'") ;
}
NOTE: PLEASE AVOID USING php mysql* class for database queries, it has been deprecated and should not be used, Switch to PDO or MySQLi. PDO reference - http://php.net/manual/en/book.pdo.php
Have you tried to run your query
UPDATE INTO booking (file_path,file_name) VALUES ('$file', '$filename') WHERE noic = '(replace here the noic you want)'
On phpMyAdmin or MySql Workbench??
Why don't you try to run the query like this:
UPDATE booking SET file_path = '$file', SET file_name= '$filename' WHERE noic = '$_SESSION[noic]'
Also check If you have set the 775 permission to the /upload folder..
Hope I help you!
$image = file_get_contents($_FILES['image']['tmp_name']);
$image = mysql_real_escape_string($image);
mysql_query("UPDATE ngc set pic='" . $image "' WHERE username='" . $_SESSION["username"] . "'");
<form method="post" action="" enctype="multipart/form-data">
Upload Image :<input type="file" name="image" id="file">
<br><input type="submit" name="submit" value="Update!" class="btnSubmit">
</form>
i want to upload image to database..
Read this very nice example here: http://www.mysqltutorial.org/php-mysql-blob/
Also see this image gallery example here: http://www.anyexample.com/programming/php/php_mysql_example__image_gallery_(blob_storage).xml
BLOBs are data types in MySql database which can help you store image files in database directly.
Although a better way would be to store the file on the disk and store the path of that variable in the database.
get the Content of the file and save in database;
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
Mysql:
$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";
First of all if you want to save the entire image into the database , you must have the pic attribute type set to BLOB , here you have two options , either save the entire image into database , or save the name after uploading the images into a specified folder with a unique name each , so you can retrieve the images by name into this directory.
I'm fairly new to PHP programming and I've looked around but I'm still confused. I'm trying to update the image path in my users table and I'm not quite sure how to do it. This is the code I have for putting the image into the database and it works to insert it in, but I'm not sure how to UPDATE the image picture path in my database to use the newly inserted image as opposed to the one the user selected when they created an account.
// Make sure we didn't have an error uploading the image
($_FILES[$image_fieldname]['error'] == 0)
or handle_error("the server couldn't upload the image you selected.",
$php_errors[$_FILES[$image_fieldname]['error']]);
// Is this file the result of a valid upload?
#is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or handle_error("you were trying to do something naughty. Shame on you!",
"upload request: file named " .
"'{$_FILES[$image_fieldname]['tmp_name']}'");
// Is this actually an image?
#getimagesize($_FILES[$image_fieldname]['tmp_name'])
or handle_error("you selected a file for your picture " .
"that isn't an image.",
"{$_FILES[$image_fieldname]['tmp_name']} " .
"isn't a valid image file.");
// Name the file uniquely
$now = time();
while (file_exists($upload_filename = $upload_dir . $now .
'-' .
$_FILES[$image_fieldname]['name'])) {
$now++;
}
// Finally, move the file to its permanent location
#move_uploaded_file($_FILES[$image_fieldname]['tmp_name'], $upload_filename)
or handle_error("we had a problem saving your image to " .
"its permanent location.",
"permissions or related error moving " .
"file to {$upload_filename}");
$insert_sql = "UPDATE users set user_pic_path WHERE user_id = $user_id =
replace(user_pic_path, '$upload_filename', '$upload_filename' );
//insert the user into the database
mysql_query($insert_sql);
</code>
EDIT:
I was missing a " which I fixed and now there is no SQL error, it puts the picture into the database but does not replace the image path in the database. I've been messing with the $insert_sql but it still doesn't update the database with the new image path, what can I do? Here's my new update code:
<code>
$insert_sql = "UPDATE users WHERE user_id = $user_id set user_pic_path =
replace(user_pic_path, '$upload_filename', '$upload_filename')";
</code>
In the final lines, insert a test of your SQL:
$insert_sql = "UPDATE users WHERE user_id = $user_id set user_pic_path = replace(user_pic_path, '$upload_filename', '$upload_filename')";
// check the query
echo $insert_sql."<br />";
//insert the user into the database
mysql_query($insert_sql);
Then you can watch the query your about to run, test it in PHPMyAdmin, work out what it should be. It's worth doing for other key variables as well. Even better, you should write a "debug" function, that logs what's going on in a file on the server so that when an error occurs, you can track details of it, including values of key variables in every file.
I am trying to create a script that has a basic file upload button and a form function. I am also trying to make a script that would be a file manager with all the input data from the form.
Form Layout:
Browse (Button) ----> When clicked prompts the user to upload only pdf files.
File Name (Form): ----> The user must put a file name
Brief Description (Form): ----> The user must put a brief description of their file
Upload (Button): ----> Once this button is hit the file is uploaded to my web server to a folder called 'files'.
File Browser Layout:
The file browser would be a table that would display all the files uploaded using the previous form. Each column in the table would show the size of the file, and show the information the uploader posted in 'File Name' and 'Brief Description'
My guess is I would need some sort of SQL database that the form information would be stored. Then I would need to make a file browser that displayed the stored information. I am not sure how to go about this task. I would really appreciate your help or ideas. Thank you for your time.
I've just wrote this without checking the errors.... here goes...
1) Create the form in upload.php
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
description <textarea name="description" cols="15" rows="15"></textarea><br>
<input type="submit" value="Upload File" />
</form>
2) create mysql table
CREATE TABLE `uploads` (
`ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`filename` TEXT NOT NULL ,
`description` TEXT NOT NULL
) ENGINE = INNODB;
3) create uploader.php and put your credentials in mysql to match the user / pass of mysql
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
// Make a MySQL Connection
mysql_connect("localhost", "admin", "1admin") or die(mysql_error());
mysql_select_db("uplodas") or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO uplods
(ID, filename, description) VALUES("","'.$_FILES['uploadedfile']['name'].'", "'.mysql_real_escape_string($_POST['description']).'" ) ")
or die(mysql_error());
echo "File Uploaded!";
This will allow you to have a working upload script.
a simple file manager will be
// Make a MySQL Connection
mysql_connect("localhost", "admin", "1admin") or die(mysql_error());
mysql_select_db("uplodas") or die(mysql_error());
// Make a MySQL Connection
$query = "SELECT * FROM uploads";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['filename']. " - ". $row['description'] ." - DELETE | EDIT";
?>
use UPDATE and DELETE mysql queries to create your delete and edit buttons.
Hope this help!