I'm having issue uploading a BLOB into my MySQL database and get the following error:
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 '()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄ' at line 1
I know the error is resulting in the image's file contents but I can't figure out what's wrong with the syntax. Any suggestions? Thanks!
Here's the PHP:
$file = $_FILES['image']['tmp_name'];
// If there's no file selected when button is pressed, echo out and tell the user to select an image to upload
if (!isset($file))
echo "<p>Please select an image to upload.</p>";
else {
//mysql escape string
$image = file_get_contents($_FILES['image']['tmp_name']);
//and here
$image_name = $_FILES['image']['name'];
$imagesize = getimagesize($_FILES['image']['tmp_name']);
}
// Checks that the file being uploaded is an image, i.e. has a size attribute with height & width dimensions
if ($imagesize == FALSE)
echo "<p>Please upload only an image file such as .jpg or .png.</p>";
else {
$sql = "INSERT INTO design (id, caption, image) VALUES ('', '$image_name', '$image')";
$result = mysql_query($sql);
if (!$result)
echo "<p>Something went wrong.</p>" . mysql_error();
else {
echo "<p>Thank you for submitting your design.</p>";
}
}
Apparently the image file contents has an apostrophe in it. That's not that surprising. You need to properly escape the input (and all inputs for that matter).
$image = mysql_real_escape_string($_FILES['image']['tmp_name']);
Instead of using ext/mysql, you should use properly parameterized queries with mysqli or PDO. Then you don't have to escape explicitly.
Related
I am working in php I want browse and upload the image file
this is my php code
<?php
if(isset($_POST['submit']))
{
$link= mysql_connect('localhost','root','');
mysql_select_db('bawa');
if(isset($_FILES['image']) && $_FILES['image']['size'] >0)
{
//Temporary file name stored on the server
$tmpname = $_FILES['image']['tmp_name'];
//read a file
$fp = fopen($tmpname,'r');
$data=fread($fp,filesize($tmpname));
$data=addslashes($data);
fclose($fp);
$query = ("UPDATE user_summary SET image='$data' where user_id=2");
$query .= "(image) VALUES ('$data)";
$results = mysql_query($query,$link);
echo "Working code";
}
else{
echo mysql_error();
}
}
?>
when i click on submit button my image should updated in my database but its not updating in database
any help?
The main problem at the moment is the line...
$query .= "(image) VALUES ('$data)";
This looks more like something that would be part of an INSERT statement. Commenting this out should mean the UPDATE should be correct.
Although as pointed out - you should work towards updating this to use either PDO or mysqli libraries and using prepared statements and bind variables.
If I try to submit an image, the echo works. So i'll see "it works". But when I check my db, it is not inserted.
userId is a INT and foreign key to the id in another table and image is a BLOB.
code:
$userId = $_SESSION['id'];
if(isset($_POST['submit'])){
$imgName = $_FILES['image']['name'];
$imgData = $_FILES['image']['tmp_name'];
$getImgData = file_get_contents($imgData);
$imgType = $_FILES['image']['type'];
if(substr($imgType, 0,5) == "image"){
$query = "INSERT INTO projects (userId, image)
VALUES ('$userId', '$getImgData')";
$result = $db->query($query);
echo "it works!";
} else{
echo "only images are allowed";
}
}
?>
The echo works, but it won't insert. Please help with this, I've been stuck for hours now!
why insert the image in the db, just get the img path (upload folder) or name and insert it, in your code you can show your image by referencing it's path, except if you must insert it as blob you can refer to this posts
http://www.mysqltutorial.org/php-mysql-blob/
I am trying to update images in my upload folder and mysql database the file uploads giving the file name 0.jpg instead of the normal persons id 13.jpg and does not update in mysql database, here is my snippet below what am i doing wrong?
$pic = mysql_real_escape_string(htmlspecialchars($_FILES['photo']['name']));
//This gets all the other information from the form
$pic=($_FILES['photo']['name']);
$file = $_FILES['photo']['name']; // Get the name of the file (including file extension).
$ext = substr($file, strpos($file,'.'), strlen($file)-1);
if(!in_array($ext,$allowed_filetypes))//check if file type is allowed
die('The file extension you attempted to upload is not allowed.'); //not allowed
if(filesize($_FILES['photo']['tmp_name']) > $max_filesize) //check that filesize is less than 50MB
die ('The file you attempted to upload is too large, compress it below 50MB.');
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("office") or die(mysql_error()) ;
//Writes the information to the
$target = "images/" .mysql_insert_id() . $ext;
$staff_id = mysql_insert_id();
$new_file_name = mysql_insert_id() . $ext;
//I removed ,photo='$target' to display only id as picture name
mysql_query("UPDATE development SET photo='$new_file_name' WHERE staff_id=$staff_id");
//Writes the file to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['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.";
}
?>
Instead of this
$staff_id = mysql_insert_id();
$new_file_name = mysql_insert_id() . $ext;
//I removed ,photo='$target' to display only id as picture name
mysql_query("UPDATE development SET photo='$new_file_name' WHERE staff_id=$staff_id");
do something like thus
mysql_query ("INSERT INTO development (photo) VALUES ( '".$new_file_name."' )");
//first insert
$staff_id = mysql_insert_id() ;
// then get the id of the record you've just inserted
Firstly, you're using the mysql_* functions, which are deprecated as of 5.5.
Secondly, you need to look at the manual page for mysql_insert_id. Quote:
Retrieves the ID generated for an AUTO_INCREMENT column by the
previous query (usually INSERT).
This means that you can only call mysql_insert_id() AFTER you've inserted data into or updated your users/persons table. In your case, however, it seems as though you already have the ID of the person stored in the variable $staff_id, so you probably don't even need to use mysql_insert_id. Would this not work instead?
$target = "images/" . $staff_id . $ext;
I am only starting with PHP and as a part of exercise I wanted to design small website that allows you to upload image and then display all uploaded images
I got the image upload succesfully working and images are stored in database but I cant find the way to display images in table along with other data
$i=0;
while ($row = mysql_fetch_array($result))
{
echo '<td>'.mysql_result($result,$i,0).'</td>';
echo '<td>'.mysql_result($result,$i,1).'</td>';
echo '<td>'.mysql_result($result,$i,2).'</td>';
echo '<td>'.mysql_result($result,$i,3).'</td>';
echo '<td>'.base64_encode($result,$i,4).'</td>';
echo '<tr>';
$i++;
How to modify the code so the image is displayed?
this is code used to upload image
if (isset($_FILES['photo']))
{
#list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use # to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title',
data='$data'");
This is where I test it enter link description here
I was looking at Stack Overflow examples, but I couldn't find any that has the loop in it with data outputted into a table.
As you are starting with PHP, you should start with the right foot :)
Don't use mysql_* functions, these are deprecated. Instead, use mysqli_* or PDO
Storing images in the DB is "a bad idea", you better store the files in the file system (a-k.a. the HD) and reference the name to a field in the DB.
Instead of mysql_fetch_array, try with mysql_fetch_assoc so you can call the fields by name. i.e.: $row['db_field_name'];
About your problem, you will need a extra script to display the stored image. Something like this:
<?php
...
$row = mysql_fetch_assoc($result);
header("Content-type: image/jpeg"); //Set the correct image type.
echo $row['data'];
exit;
?>
And in your display html:
...
<img src="yourscript.php?image=XX" ...>
...
Hope this help :)
I am in the early stage of developing a bidding system whereby users are able to insert items that they want to sell. Here is the script to copy the image from the temporary path and store the path of the image to another folder.
define ("MAX_SIZE","10000");
//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
};
//This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
$errors = 0;
//Checks if the form has been submitted
if (isset($_POST['Submit']))
{
//Reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//If it is not empty
if ($image)
{
//Get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//Get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//If it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests
if (($extension != "jpg") &&
($extension != "jpeg") &&
($extension != "png") &&
($extension != "gif"))
{
//Print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//Get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//Compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*111111111111024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//We will give an unique name, for example the time in Unix time format
$image_name=time().'.'.$extension;
//The new name will be containing the full path where will be stored (images folder).
$imagepath='C:\\xampp\\htdocs\\biddingsystem\\Images\\' . $image_name;
//We verify if the image has been uploaded, and print an error instead
$copied = copy($_FILES['image']['tmp_name'], $imagepath);
if (!$copied)
{
echo '<h1>Picture upload failed!</h1>';
$errors=1;
}
}
}
}
//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors && isset($_POST['image']))
{
echo "<h1>Picture Uploaded Successfully! Try again!</h1>";
}
Then, I inserted the image path along with other data to a MySQL database with the script below and tried to display them back to the user using a table. Other data worked out fine but for the image display (imagepath), only the path of the image gets displayed, not the image itself.
mysql_query("INSERT INTO items
(username, item, price, description, start_date, start_time, imagepath)
VALUES ('$username', '$_POST[item]', '$_POST[price]', '$_POST[description]','$_POST[start_date]', '$_POST[start_time]', '$imagepath') ")
or die ("Error - Couldn't add item");
echo "Item added successfully";
echo "<h1>You have added the following item:</h1>";
$sql = "SELECT item, price, description, start_time, start_date, imagepath FROM items WHERE username = '$username' AND item='$_POST[item]'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo"<table border=2>
<tr><td>Item</td>
<td>Price</td><td>Description</td><td>Start time</td><td>Start date</td><td>Picture</td></tr>
<tr><td> $row[item]</td>
<td> $row[price]</td>
<td> $row[description]</td>
<td> $row[start_time]</td>
<td> $row[start_date]</td>
<td> $row[imagepath]</td>
</tr>
</table></br>";
I have tried using <img src="<?php $imagepath ?>"> to show the image but to no avail. I have even tried storing the actual image itself in the database using the BLOB type. However, the result is a page filled with strange characters. How do I fix this problem?
You are confusing the filesystem path and web URL. You have to store only /biddingsystem/Images/ part or even just only name and generate full path dynamically at display time.
Also note that you aren't formatting your data properly, which will lead to some bugs and security vulnerabilities. I've explained formatting rules in my earlier answer, to Stack Overflow question How to include a PHP variable inside a MySQL insert statement.
If you want to go with the first solution, displaying from a path, make sure you're pointing to the image in an accessible path. From the code you listed, it looks like $imagepath is a file:// path. On a web server, you'll have to map that to a relative web path.
If you decide to go with the BLOB, the best method is to make a separate page that serves images. Your output image tags should point to that and you need to change the content type in the header of the image service page.