Image rename and value insert into my mysql - php

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.

Related

Uploading Image works but doesn't store into Databse

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

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();

php form does not save date into database

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.

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;

Storing the changed filename into mysql field

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.

Categories