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>
Related
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!
I am trying to store the image in database using the blob datatype.
but my program was not storing the image in database.
code:
form.php:
<form action="upload.php" method="post" enctype="multipart/form-data">
File Name<input type="file" name="image" /><br />
<input type="submit" value="Upload" />
</form>
upload.php:
<?php
require_once('connection.php');
if(isset($_POST['submit'])){
$image = addslashes(file_get_contents($_FILES[image]['tmp_name']));
$query = "INSERT INTO images ('image') VALUES('".$image."')";
mysql_query($query) or die(mysql_error());
echo "Image id is ".mysql_insert_id();
echo "Image id is ".mysql_insert_id();
}
?>
please resolve my problem..
A BLOB can store 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.
Look at Storage Requirements for String Types.
My suggestion is use LONGBLOB instead of BLOB.
Hope it will works.
try to use the below code.
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$query = "INSERT INTO images (image) VALUES('".$image."')";
i think this time its work fine...
Try using backticks on fieldName
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
try this one.this is also another approach for storing the blob image.
code:
$image= $_FILES["image"];
$image= mysql_real_escape_string("$image");
$query = "INSERT INTO images (image) VALUES('".$image."')";
mysql_query($query) or die(mysql_error());
echo "Image id is ".mysql_insert_id();
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 want to get this image uploading script right, but for whatever reason it doesn't like the description input. It was working perfectly before I added the description input and I can't think of what might be wrong because it looks fine. My code doesn't like the description input in the form, what is wrong? Thanks for the help!
HTML Form
<h1>Image Gallery</h1>
<form enctype="multipart/form-data" action="upload.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
Description: <textarea maxlength="255" name="description" id="description"></textarea><br />
<input type="submit" value="Upload" />
</form>
PHP Code (There is code before this but it doesn't matter)
$userid = mysql_real_escape_string($_SESSION['UserID']);
$imageid = mysql_real_escape_string($i);
$image = mysql_real_escape_string($rename);
$description = mysql_real_escape_string($_POST['description']);
$registerquery = mysql_query("INSERT INTO imageupload (UserID, ImageID, Image, Description) VALUES('".$userid."', '".$imageid."', '".$image."', '".$description."')");
if($registerquery) {
header( 'Location: manage.php' ) ;
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, an error occured. Please go back and try again.</p>";
}
What datatype is the column for description?
Replace your current query with:
$description = mysql_real_escape_string(strip_tags(stripslashes($_POST['description'])));
$register = "INSERT INTO imageupload (UserID, ImageID, Image, Description) VALUES('$userid', '$imageid', '$image', '$description')";
$registerquery = mysql_query($register) or die (mysql_error());
if($registerquery) {
header( 'Location: manage.php' ) ;
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, an error occured. Please go back and try again.</p>";
}
Maybe the description you insert contains strange characters for db like ";' and so on...?
In case escape the description you get from post with your database php library escaping function... This is also a good practice to avoid sql injection
If you use mysql: http://www.php.net/manual/en/function.mysql-real-escape-string.php
Try replacing
$description = $_POST['description'];
with
$description = mysql_real_escape_string($_POST['description']);
Print out the query and try run it on the mysql command line interface, does it give an error?
you're not cleaning the description string so open to injection there too.
I have this form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="change" value="Update Image!" />
</form>
and this action here :
if(isset($_POST['change']))
{
$id = $_POST['id'];
$img = "photo_gallery/" .$_FILES["file"]["name"];
$query = "UPDATE gallery SET image =\"{$img}\" WHERE id = $id";
$up = mysql_query($query, $connection);
if(!$up){
echo die(mysql_error());
echo "error,not updated!";
}
}
The error is:
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
Any help for finding the error please!
You are not passing the id value in your form.
As a side note: you are exposed to a SQL injection attack both via the id parameter, as well as the file parameter... And if you pass the id in the form you may allow to maliciously alter images that were not intended to update.
=== Below: edited by someone else. As a note: htmlentites will not guard against SQL injection (use mysql_real_escape), and md5 will guard against injection but not against file overwriting (if someone uploads a file with the same name it will clash). Moreover, if you pass the ID in the form, one can change it and alter an unintended image. ===
Try to secure your code :
if(isset($_POST['change']))
{
$id = htmlentities($_POST['id']);
$img = "photo_gallery/" .md5($_FILES["file"]["name"]);
$query = "UPDATE gallery SET image =\"{$img}\" WHERE id = $id";
$up = mysql_query($query, $connection);
if(!$up)
{
echo die(mysql_error());
echo "error,not updated!";
}
}