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!
Related
my problem is that i have a form that was supposed to save information about a comic book into a database, the information it is saving is title, description etc, also it is uploading an image of the comic to my server.
right now it does upload the image to the server, but it does not put any information into my table, and simple don't know why?
Im pretty new php and mysql so maybe it is an easy problem but i can't figure this out, and i haven't been able to find the answer online.
my table structure:
id - int(11)
title - varchar(50)
description - text
publicer - varchar(50)
image - varchar(30)
price - int(10)
status - tinyint(1)
my form is on my index.php and looks like this:
<form method="post" action="newcomic.php" enctype="multipart/form-data">
<p>Comic name:
<br><input type="text" name="title"/></p>
<p>Description of the comic:
<br><textarea name="description"></textarea></p>
<p>Publicer:
<br><input type="text" name="publicer" /></p>
<p>Image:
<br><input type="file" name="image" /></p>
<p>Price:
<br><input type="text" name="price" /></p>
<p><input type="submit" name="add" title="Add new comic to database" value="Add Comic"/></p>
</form>
And my my newcomic.php file is looking like this
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$title = $_POST['title'];
$description = $_POST['description'];
$publicer = $_POST['publicer'];
$image = ($_FILES['image']['name']);
$price = $_POST['price'];
// Connects to your Database
mysql_connect("localhost", "root", "root") or die(mysql_error()) ;
mysql_select_db("comic_express") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO products (id, title, description, publicer, image, price, status)
VALUES ('', '$title', '$description', '$publicer', '$image', '$price', '1')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Hope that anyone can help me :)
Wrong sql syntax. You are trying to put empty string in id.
You should add some error handling to your query execution to help find what's happening.
Basic mysql error handing in php would be something like:
<?php
$link = mysql_connet(CREDS HERE);
$query = "YOUR QUERY HERE";
$result = mysql_query($query, $link);
if(!$result)
echo mysql_error();
else
//Query was successful, do whatever here
?>
You always want to make sure you that the query was successful, even if you're confident that it will.
I believe Guarana is right on this one as well, just take the id out (if you set up the table properly the id will be auto generated) or you will need actually insert the id instead of empty string.
hope this helps!
you must use mysql_error() function along with your query. so that you can found the eject problem in your sql query string.
use given edited code and try.
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$title = $_POST['title'];
$description = $_POST['description'];
$publicer = $_POST['publicer'];
$image = ($_FILES['image']['name']);
$price = $_POST['price'];
// Connects to your Database
mysql_connect("localhost", "root", "root") or die(mysql_error()) ;
mysql_select_db("comic_express") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO products (title, description, publicer, image, price, status)
VALUES ('$title', '$description', '$publicer', '$image', '$price', '1')") or die(mysql_error()) ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
oh yes you are inserting blank value in integer type field. check that it is primary key with auto increment. if yes leave this column means you have no need to insert it.
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.
I am trying to save images in my database from HTML form. I have written PHP code to accomplish this task. The program is not generating any error message, but also not inserting image data in MySQL database. Kindly check it.
Here i am sharing a excerpt from my code.
/*-------------------
IMAGE QUERY
---------------*/
$file =$_FILES['image']['tmp_name'];
if(!isset($file))
{
echo 'Please select an Image';
}
else
{
$image_check = getimagesize($_FILES['image']['tmp_name']);
if($image_check==false)
{
echo 'Not a Valid Image';
}
else
{
$image = file_get_contents ($_FILES['image']['tmp_name']);
$image_name = $_FILES['image']['name'];
if ($image_query = mysql_query ("insert into product_images values (1,'$image_name',$image )"))
{
echo $current_id;
//echo 'Successfull';
}
else
{
echo mysql_error();
}
}
}
/*-----------------
IMAGE QUERY END
---------------------*/
<form action='insert_product.php' method='POST' enctype='multipart/form-data' ></br>
File : <input type='file' name= 'image' >
</form>
Error Message
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '' at line 1
Firstly, you should check if your image column is BLOB type!
I don't know anything about your SQL table, but if I'll try to make my own as an example.
We got fields id (int), image (blob) and image_name (varchar(64)).
So the code should look like this (assume ID is always '1' and let's use this mysql_query):
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
echo "Something went wrong! :(";
}
You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.
Also your HTML form is out of standards. It should look like this:
<form action="insert_product.php" method="POST" enctype="multipart/form-data">
<label>File: </label><input type="file" name="image" />
<input type="submit" />
</form>
Sidenote:
When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string(), otherwise it will result in a syntax error.
Just few more details:
Add mysql field
`image` blob
Get data from image
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
Insert image data into db
$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";
Show image to the web
<img src="data:image/png;base64,'.base64_encode($row['image']).'">
End
This is the perfect code for uploading and displaying image through MySQL database.
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
if(isset($_POST['submit']))
{
if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
{
echo " error ";
}
else
{
$image = $_FILES['image']['tmp_name'];
$image = addslashes(file_get_contents($image));
saveimage($image);
}
}
function saveimage($image)
{
$dbcon=mysqli_connect('localhost','root','','dbname');
$qry="insert into tablename (name) values ('$image')";
$result=mysqli_query($dbcon,$qry);
if($result)
{
echo " <br/>Image uploaded.";
header('location:urlofpage.php');
}
else
{
echo " error ";
}
}
?>
</body>
</html>
I created a login page that when user login redirect to a pictures.php,
pictures page should contains the images of the user , I already create upload page to upload image to file directory and when the user upload an image the image link is added to a new row in the database, I need to add the image link to an exist row of the user,I already created a session for user when logged in.
So I need to add the image link to an exist row of the user.
This is the code that insert the image to a file directory and save its link to a new row of the database.
<?php
$name = $_FILES["myfile"] ["name"];
$type = $_FILES["myfile"] ["type"];
$size = $_FILES["myfile"] ["size"];
$temp = $_FILES["myfile"] ["tmp_name"];
$name = $size.$size .$name ;
$error = $_FILES["myfile"] ["error"];
if ($error > 0){
die ("Error uploading image");
}else{
mysql_query("INSERT INTO userid (imageid) VALUES ('.$name')");
move_uploaded_file($temp,"uploaded/".$name);
echo "Upload Completed";
}
?>
And the upload form is
<html>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="Submit" value="Upload">
</form>
</html>
So how to the image link to an exist row of the user.
Use mysql_query("UPDATE $table_name SET imageid='{$name}' WHERE userid=$userid")
Of course substituting variables and columns with correct values
Use UPDATE query instead of INSERT. INSERT will add new row but UPDATE will update your existing data.
You have to update the row if the row where you want to add image link is already exist. So use UPDATE Query. and debug wether table is updated or not.
check in table or use or die(); after the query
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!