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;
Related
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
I have a peace of code that stores profile images in the map "images/profiles" and stores the URL in the database. I want to define the name of the uploaded profile picture to be the $ID of the user. How can I do this?
include("../../core/init.inc.php");
$target = "../images/profiles/";
$target = $target . basename($_FILES['photo']['name']);
$pic = $_FILES['photo']['name'];
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
echo "The file ". basename($_FILES['photo']['name']). " has been uploaded";
} else {
echo "ERROR";
}
mysql_query("UPDATE users SET image_url='includes/images/profiles/$pic' WHERE username = '".mysql_real_escape_string($_SESSION['username'])."'");
Now when someone uploads his profile picture (lets call it pf1.png) it saves it as "pf1.png". I want it to be saved like "$ID.png" (.png being a random extension). I want to accomplish this both for the move_upload_file function and updating the 'image_url' database column correctly.
According to the example in the documentation you can provide the filename in the destination of move_uploaded_file(). If that fails you can simply rename() the file after saving it.
try changing
$target = $target . basename($_FILES['photo']['name']);
to:
$filename=$_FILES["file"]["tmp_name"];
$extension=end(explode(".", $filename));
$target = target . $_SESSION["ID"].".".$extension;
side note: You are not escaping $pic this makes your site vulnerable to sql-injection
I don't know how you saved the ID of the user, but to make it easy let's assume you stored the ID in a session.
Then simply change the $target.
$target = $target . $_SESSION['ID'];
Also change your query as follows:
$url = "includes/images/profiles/" . $_SESSION['ID'];
SET image_url="$url"
Note: I don't know why you got an image folder inside an includes folder, but I guess you made that choice for yourself.
you can get the last inserted id and make it as a name of your image/uploaded file
$qry = mysqli_query($dbconnection,"INSERT INTO statements here");
$last_id = mysqli_insert_id($dbconnection);
//$ext= you get the extension of the file uploaded
move_uploaded_file($tmpname,$target.$last_id.$ext);
now if you want it to be accomplished in updating also.
you can always get the ID of the data you want to fetch and make it as a basis in updating.
ex.
$id = $_GET['id'] || $id = $row['id']; //anything depends on how you want it to retrieve
then you can do the query and move_uploaded_file function
$qry = mysqli_query($dbconnection,"UPDATE tblname SET field='$anything' WHERE id = '$id'");
move_uploaded_file($tmpname,$target.$id.$ext);
of course $tmpname will be the basis on what file you have uploaded, $tmpname will be the file you want to move into your desired directory
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.
I have a form wherein users can upload images and these images are being saved on a particular folder in the server. At the same time the filename of the photo is being stored in a particular field in a MySQL table.
I tried changing the filename by adding a timestamp (and it works) however this new filename is not the filename being stored on the MySQL field meaning it stores the original photo filename from the user.
Is there a way that the new filename will be the one stored on MySQL table.
Below is the code I am using:
enter code here
//This is the directory where images will be saved
$target = "pics/";
$target = $target. basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$pic=($_FILES['photo']['name']);
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$pic')") ;
//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['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.";
}
?>
I want the file to be renamed into something unique and I want that unique filename be stored on the photo field of my SQL table.
Before inserting, save the new filename into a variable, then change the name, and insert the new name into the database finally.
Or, If you want to change the name after you've done the insert, run an UPDATE query on the table, where you update the filename:
UPDATE table SET filename = 'new_filename' WHERE filename = 'old_filename"
Heres some code I just wrote which does a count on how many files are currently in the system and increments it by one thus making it a unique file_name, if every file is for example "user_1.jpg" and so on.
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("database") or die(mysql_error()) ;
//handle the form information
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
//handle our file
$photo = $_FILES['photo']['tmp_name'];
//set where the file is ment to go
$target = "pics/";
//get the base name of the file
$filename = basename($photo);
//get the extension of the requested file
$extension = substr($filename, strrpos($filename, '.') + 1);
//count the length of items in the string
$stringLength = strlen(basename($photo));
//Get the file path of the photo minus the name of the photo
$filePath = substr($photo, 0, - $stringLength);
//set the inital name of the file
$PhotoName = "username.jpg";
//set the full path and name of the file to be uploaded
$checkThisFile = $target . $PhotoName;
//count how many files are in the folder and increment it by 1 in the while loop
$filecount = count(glob($target. "*.jpg"));
//while the file can be found in the system
while(file_exists($checkThisFile)){
//increment the count till the file is unquie
$filecount++;
//change the name of the file
$PhotoName = "username_$filecount.jpg";
//set the target and name of the file to be uploaded to keep testing it through our loop
$checkThisFile = $target . $PhotoName;
//if the file is not in the system then
if(!file_exists($checkThisFile)) {
//break the while loop
break;
} //end if condition
} //end while loop
//rename the photo file from the temporary name to the full name of the file
if($renamedFile = rename("$photo", "$checkThisFile")) {
//print a success tha our file was renamed
echo "<br/>the file was renamed";
//check if our renamed file exists
if(!empty($renamedFile)) {
//print a success that our file is there
echo "<br/>The renamed file exists!";
//move the uploaded file!
if(move_uploaded_file($renamedFile, $target)) {
//print there was an error with the transfer
echo "cannot move files!";
} //end he if condition
else {
//write to the database
$MyDatabaseQuery = "INSERT INTO employees VALUES ('','$name', '$email', '$phone', '$PhotoName')";
//run the query
#mysql_query($MyDatabaseQuery);
} //end else condition
} //end if condition
} //end if condition
The point of the code is too keep running through the loop till the file is not in the system and then rename the temporary file and upload it then store only the name of the file+extension in the database with any other records you want to store. I hope this helped.
Here is the MySQL Create TABLE Script too
CREATE TABLE IF NOT EXISTS `employees` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`email` text NOT NULL,
`phone` text NOT NULL,
`picture` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
You'd have to make a system for this, since the server can't decide to make a mysql-query each time you change the name of a file.
You'd have to have some kind of admin where you present all your files in a directory, and do a command which changes both the filename and the mysql-row.
i have been stressing for an hour at this stupid script i am trying to make it uploa an MP3
file to a folder it creates.
It is putting the information into mysql and making the folder bu when i ftp the folder is empty with no music file in there
here is the script thanks so so so much!
BTW $name is the POSTED name and full name is the posted name + ".mp3"
// BEGIN ENTERING INFORMATION TO MYSQL TABLE
$sql = mysql_query("INSERT INTO mattyc (name, date, length, size, link)
VALUES('$name','$date','$length','$size','$link')"
) or die (mysql_error());
mkdir("../music/albums/donjuma/$name", 0777);
$song = ("../music/albums/donjuma/$name/$fullname");
if (file_exists($song)) {
unlink($song);
}
$newname = "$fullname";
$newfile = rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file( $newfile, "../music/albums/donjuma/$name/"."$newname");
$success_msg = "<font color=\"#009900\">Your SONG has been updated, it may take a few minutes for the changes to show... please be patient.</font>";
echo $success_msg;
}
}
}
$newfile =
rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file(
$newfile,
"../music/albums/donjuma/$name/"."$newname");
rename() returns a bool, not a filename. So your move_uploaded_file() call is going to fail. Any file renaming should be part of your move_uploaded_file() call, don't try and do anything with your temporary file apart from move it.