Ok, this one is driving me nuts. I have a backend file uploader that uploads .jpg files to the server. Then I want to upload the filename(s) of the .jpgs to my database. So when the page loads I can add the filename from the database and the pictures will display on the page. This works fine, but I also need to be able to update the files and the filenames in the database. If the user changes all the files and file names everything is fine. But if the user wishes to change only one or two file(s) and filename(s) the MySql update statement ends up having some of the variables empty thereby effectively deleting the existing filenames in the record instead of leaving them alone. As usual I have searched stackoverflow and google before asking for help and I have not found anything that is really pertinent. Here is the applicable code.
<?php
session_start();
$id = $_SESSION['id'];
//This is the directory where images will be saved
$target = "imgs/";
// "http://www.surfcup.com/travel_site/images/ ";
$targetlogo = $target . basename( $_FILES['imageLogo']['name']);
$targetpic1 = $target . basename( $_FILES['image1']['name']);
$targetpic2 = $target . basename( $_FILES['image2']['name']);
$targetpic3 = $target . basename( $_FILES['image3']['name']);
$targetpic4 = $target . basename( $_FILES['image4']['name']);
$targetpic5 = $target . basename( $_FILES['image5']['name']);
//This gets all the other information from the form
$logo=($_FILES['imageLogo']['name']);
$pic1=($_FILES['image1']['name']);
$pic2=($_FILES['image2']['name']);
$pic3=($_FILES['image3']['name']);
$pic4=($_FILES['image4']['name']);
$pic5=($_FILES['image5']['name']);
// Connects to Database
mysql_connect("localhost", "surfcup_HotAdmin","password") or die ('I cannot connect to the database because: ' .mysql_error());
mysql_select_db("surfcup_hotels") or die('I cannot connect to the database because: .mysql_error());
$query="UPDATE Hotels
SET
hotel.imageLogo = '".$logo."',
hotel.image1 = '".$pic1."',
hotel.image2 = '".$pic1."',
hotel.image3 ='".$pic1."',
hotel.image4 = '".$pic1."',
hotel.image5 = '".$pic1."'
WHERE Hotels.id='".$id."'";
mysql_query($query) or die ('Error Updating Hotel '.mysql_error());
//stuff to upload the files below
?>
I think I either need to check if the variables are null and somehow not up load them or stop the database from accepting null entries. The later though would make the user have to add 6 files when he/she creates a record. What if they only had 5 or 3? I can't seem to get my head around how I would check if the variables are null and only upload the ones with filenames in them in the UPLOAD statement. Thanks again, in advance, for all your help.
Dave
I think a better way of doing this is to build your query dynamically. For example:
$images = array();
$images[] = ($_FILES['imageLogo']['name']);
$images[] = ($_FILES['image1']['name']);
$images[] = ($_FILES['image2']['name']);
$images[] = ($_FILES['image3']['name']);
$images[] = ($_FILES['image4']['name']);
$images[] = ($_FILES['image5']['name']);
// Looping index to determine which hotel image it is
$index = 0;
// Start building query
$query = "UPDATE Hotels SET hotel.imageLogo = '".$images[0]."'";
// Loop through images and check if empty string
foreach($images as $image)
{
if(!empty($image) && $index != 0)
{
// Image name found, add to query
$query .= " hotel.image".$index." = '".$image."',";
}
// First hotel image iteration needs to be 1
$index++;
}
// Finish query
$query .= " WHERE Hotels.id='".$id."'";
You can try this. Basically it checks if the value is empty. If it is not, then it adds the value to the array. At the end we implode the array into a string that we will add to the your query. In the example I only did a few of the images, but you should get the point. It should work barring syntax errors in my code.
Although I will say that this is not the best way to do it. You can definitely improve on this and make it more secure and efficient.
$uploaded_images = array();
if(!empty($logo)){
$uploaded_images[] = "hotel.imageLogo = '".$logo."'";
}
if(!empty($pic1)){
$uploaded_images[] = "hotel.image1 = '".$pic1."'";
}
if(!empty($pic2)){
$uploaded_images[] = "hotel.image2 = '".$pic2."'";
}
$values_to_set = implode(', ', $uploaded_images);
$query= "UPDATE Hotels SET " . $values_to_set . " WHERE Hotels.id='" . $id . "'";
Related
I am trying to upload two images with php. And add them to the database. Somehow it only uploads one image and the records in the database always have the same values.
this is the code i use
<?php
include "../connect.php";
$name1 = $_FILES['pic1']['name'];
$size1 = $_FILES['pic1']['size'];
$name2 = $_FILES['pic2']['name'];
$size3 = $_FILES['pic2']['size'];
if(isset($_POST['name']))
{
$extension1 = pathinfo($name1,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension1,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image1 = time().'.'.$extension1;
$file1 = "images/upload";
$pic1 = "$file1/".$new_image1;
move_uploaded_file($_FILES["pic1"]["tmp_name"],"../".$pic1."");
$insert = mysql_query("update temp set pic='$pic1' ") or die("error ins");
}
$extension2 = pathinfo($name2,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension2,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image2 = time().'.'.$extension2;
$file2 = "images/upload";
$pic2 = "$file2/".$new_image2;
move_uploaded_file($_FILES["pic2"]["tmp_name"],"../".$pic2."");
$insert = mysql_query("update temp set passport='$pic2'") or die("error ins");
}
}
?>
One of the problems you have is with your update statement. There is no 'where' statement saying which record in the database should be updated so this query updates them all. That's why you only have the last image in all the database rows.
Besides that, your code is not very good from a security point of view. You should take a look at mysqli or pdo for your database connection and queries because MySQL is deprecated and removed from PHP. Also take a look at SQL injections and data validation. Besides some very basic extension and size validation there is nothing there to keep things save. Try escaping and validating all user inputs.
And another point would be to take a look at 'functions'. You're running almost the exact same piece of code at least twice. And every code change has to be done twice. Perfect for a function call, something like
function storeImage($image){
// write the uploading and storing PHP here
}
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
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.
I'm having a brain dead moment... If someone could talk this through with me and make suggestions that'd be great.
I'm importing a URL from a database, eg www.mysite.com/images/image1.jpg set as variable newimage1
This is loaded from the DB and placed on the page.
As this is an edit page, the user can upload a new image.
If the user doesn't upload a new image, but saves the page anyway, the variable newimage1 is not set, it clears the existing image url from the database because the variable is set to "".
What's the best way to do this? An if statement, that checks if newimage1 is blank and removes it from the update to the database?
Sorry for this simple question!
$image_name = "";
if(!empty($_FILES)){
$image_name = $_FILES['image']['tmp_name'];
}
$sql = "UPDATE table SET var1 = 'value1', var2='value2'";
if($image_name != "")
$sql .= ", image_name = '".$image_name."'";
$sql .= " WHERE id_entry = 5";
if( empty($_REQUEST['newImage1']) ) {
//program logic
} else {
//program logic
}
I have the following code that is used to load user images from a database when their information is displayed.
I was attempting to write it in a way in which it would check if the user already has an image tied to their user id in the database and if so, would leave the image alone and if not, would display a "missing.jpg"/default user image.
I've tried the following, but right now it seems the code is overwriting existing images and replacing them with the missing.jpg image and I don't know why.
I'd appreciate somebody taking a look and showing me why that is.
//Images
$thisScript = $_SERVER["SCRIPT_FILENAME"];
$dirName = dirname($thisScript);
$relative_path = "images/headshots/".$this->id.".jpg";
$missing_path = "images/headshots/missing.jpg";
$full_path = $dirName . "/" . $relative_path;
//if(file_exists($relative_path))
//if(file_exists($_FILES['uploadedfile']['name']))
if(basename( $_FILES['uploadedfile']['name']) != '' /*and (file_exists($_FILES['uploadedfile']['name']))*/)
{
$this->process_headshot_file($relative_path, $full_path);
}
else
{
//$this->process_headshot_file($missing_path, $full_path);
$query = "UPDATE hraps SET headshot_filename = '".$_SESSION['missing_headshot_image']."' WHERE id = ".$this->id;
$result = mydb::cxn()->query($query);
}
Thank you in advance for your help.
Your if statement here:
if(basename( $_FILES['uploadedfile']['name']) != '')
is only going to work when there's something in $_FILES
Since you say you want to display an image when their information is displayed, that's probably not going to trigger very often, so the else is going off instead.
I don't think you need to do anything more complicated than this:
$image = "images/headshots/missing.jpg";
if(file_exists($relative_path)) {
$image = $relative_path;
}
$full_path = $dirName . "/" . $image;
$this->process_headshot_file($image, $full_path);