Uploading Image works but doesn't store into Databse - php

I am trying to upload a image into my database.
The script works fine and shows no error messages. The script successfully uploads to a directory within my server called 'profilepics' however it fails to update the database with the image information, there are no errors and when I echo out the script everything works fine such as session variables, the image name field etc.
Here is my query:
$query = "UPDATE members SET image='$pic' WHERE memberID='" . $_SESSION['user'] . "'";
$result = mysqli_query($connection, $query) or exit ("Error in query: $query. ".mysqli_error());
if(move_uploaded_file($_FILES['photo']['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.";
}

UPDATE is only used when you have an existing row which you want to, update.
So use INSERT INTO, as you're inserting a new row.
Example of an INSERT INTO QUERY using your query:
$query = "INSERT INTO members(`image`) VALUES ('". $pic . "')";

thanks for the help everyone, but I found the issue silly me! the query was perfect in case anyone wanted to know, i was being stupid and didn't realize my session is a username and I was checking to see if it matches my memberID -_________________________-
Thanks again

Related

unlink() function don't work without any error

i have problem with my code and unlink function
here my code
if(isset($_GET['delimg'])){
$id= $_GET['delimg'];
$sql = "delete from images_img where id='$id'";
$res=mysqli_query($con,$sql);
$getname="select * from images_img";
$res2=mysqli_query($con,$getname);
$image=mysqli_fetch_array($res2);
$image1=$image['image_url'];
$image2=$image['image_url_big'];
unlink('../../images/photo'.$image1);
unlink('../../images/photo'.$image2);
}
when i run my delete.php in the database the images deleted just fine
but the unlink function don't work and don't delete anything from the path and no error shows !
my thought that the select way return empty value ! as i use
this $image=mysqli_fetch_array($res2); to select the images name
so any error with my code please ?
UPDATE ::
i'm sure that the delete excuted before selecting the data for name to delete >>
so how i would arraying the order ?
UPDATE 2 :::
this is the upload code
$nameimg=$_FILES['image']['name'];
$tmp=$_FILES['image']['tmp_name'];
$type=$_FILES['image']['type'];
$size=$_FILES['image']['size'];
$dir="/images/photo/";
if($_POST['upload']){
if(!empty($nameimg)){
if(in_array($type,array('image/png','image/jpg','image/gif','image/jpeg'))){
if(filesize($tmp) <= 20242880){
move_uploaded_file($tmp,$dir.$nameimg) ;
$done ="done";
}
else {$errorsize= "it's bigger than the allowed size";}
}
else {
$errortype= "the file not image,please choose image to upload";
}
}
if(empty($nameimg)){$errorchoose= "no file choosen,please choose file";}
}
echo "<meta http-equiv='refresh' content='5;url=../../admin.php#ajax/add_img.php'>";
?>
check with file exists function like below also enable php errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
$imgPath = ''../../images/photo'.$image1';
if (file_exists($imgPath)) {
unlink($imgPath);
} else {
echo "not exists";
}
ooh it's worked finally !!!
the all problem .. all time we have spend it was for nothing !
from first time and my first code it was work just fine and every code i have given by you guys it was worked .. but just we all [except "Parasad"] forgot [/] after "photo" !!!!!!! to be like this
unlink('../../images/photo/'.$image1)
not like this
unlink('../../images/photo'.$image1)
really i make you guys work hard to try slove my problem and i take your time
so million huge thanks to all of you specially [WordpressCoder] .. thanks a lot
Copy this code and tell me whether it is working or not?
if(isset($_GET['delimg'])){
$id= $_GET['delimg'];
$getname="select * from images_img where id='$id'";
$res2=mysqli_query($con,$getname);
$image=mysqli_fetch_array($res2);
$image1=$image['image_url'];
$image2=$image['image_url_big'];
$sql = "delete from images_img where id='$id'";
$res=mysqli_query($con,$sql);
unlink('../../images/photo/'.$image1);
unlink('../../images/photo/'.$image2);
}
if(isset($_GET['delimg'])){
$id= $_GET['delimg'];
$sql = "delete from images_img where id='$id'";
$res=mysqli_query($con,$sql);
$getname="select * from images_hair";
$res2=mysqli_query($con,$getname);
$image=mysqli_fetch_array($res2);
$image1=$image['image_url'];
$image2=$image['image_url_big'];
unlink('../../images/photo/'.$image1);//check your url
unlink('../../images/photo/'.$image2);//check your url
}

delete an image file using php

I am building a forum with php and MySQL and I want to append current time to each image that users upload for their profile. I used time() function on each image file uploaded and it worked for the image file but I have trouble inserting the new filename into the database. I wanted to give each image a unique name to prevent override.
OK here is what I did: I stored the current time as $time and the filename in a variable, $photo and I tried to insert that variable’s value using $photo .= $time into the database so it has the filename as I did with each uploaded image. However the original filename is inserted into the database in every attempt.
Any workarounds?
$image = $_FILES['photo']['name'];
$time = time();
$image .= $time;
delete the existing photo
delete(image_dir/$row['current_photo.jpg']);
//does not work, but i want something like that
if(move_uploaded_file($_FILES['photo']['tmp_name'], 'image_dir/$image') {
$query = "INSERT INTO profile (user_id, profile_photo) VALUES($id, $image)";
mysqli_query($dbc, $query);
if(mysqli_affected_rows($dbc) == 1) {
echo "added to the database!";
}else {
echo "failed to add photo to the database";
}
}else {
echo "failed to upload photo";
}
how can i give the uploaded image unique the name since the original image name gets inserted in the database in every try i make?
i know the code looks funny :). just want to show the logic.
If you need a unique id, you can use the uniqid function
$name=uniqid();
you may need to use
$filename=uniqid();

Image rename and value insert into my mysql

What I would like is for an uploaded image to have a random name that would would be inserted into my data base so I can call it on user profiles. I have the php code that will upload files to the local disc but no values are being submitted into the mysql row for the user. Also, all the images are being named image.jpg and overwriting each other. Any help would be great. Thanks!
<?php
//This is the directory where images will be saved
$target = "images/uploaded/user_images/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$photo=($_FILES['photo']['name']);
// Connects to your Database
mysql_connect("server", "root", "pass") or die(mysql_error()) ;
mysql_select_db("db") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `users` VALUES ('$photo')") ;
//Writes the information to the database
mysql_query("INSERT INTO photo ('name')
VALUES ('$photo')") ;
//Writes the photo 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.";
}
?>
For I start I would like to ask you how do you know which user has which picture? Becouse you just store images in table without any user ID. I suggest that you redesign your database.
Then I will use this for an image name instead of completely random string.
$_FILES['photo']['name'] = "image_" . round(microtime(true) * 1000) . ".jpg";
Or get the number of images in database and increase it by one. That way you cannot end up with multiple images with same name.

Update image path

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.

updating image in upload folder and image path in mysql

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;

Categories