how to use old profile picture if no image selected in php - php

this is my code updating data. How is it possible to use old image if no image is selected?
its a profile page when someone updates his profile but don't select the image for update then old image should be remained there..
<?php
if(isset($_POST['update_user'])){
//getting text data from field
$update_id = $user_id;
$fullname = $_POST['fullname'];
$designation = $_POST['designation'];
$username = $_POST['username'];
$location="images/users/";
$name=$_FILES['user_img']['name'];
$temp_name=$_FILES['user_img']['tmp_name'];
if(isset($name)){
move_uploaded_file($temp_name,$location.$name);
}
else
{
echo $user_img;
}
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username',User_Pic='$name' where Id='$update_id'";
$run_product = mysqli_query($con, $update_product);
if ($run_product){
echo"<scripy>alert('Update Successful')</script>";
echo "<script>window.open('user_manage.php','_self') </script>";
}
}
?>

First, you need to fetch the existing user details from the database and check if the user already has a profile picture.
Next, if the user has uploaded a new image, then you can delete the old profile picture using unlink() function. If the user has not uploaded a new picture, you can retain the old picture.
See the code below.
<?php
if(isset($_POST['update_user'])){
//getting text data from field
$update_id = $user_id;
$fullname = $_POST['fullname'];
$designation = $_POST['designation'];
$username = $_POST['username'];
$location="images/users/";
//Fetch user details
$query = "SELECT User_Pic FROM user WHERE Id=" . $update_id;
$result = mysqli_query($con, $query);
$row = false;
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
}
if (isset($_FILES['user_img'])) { //User uploaded new image
if ($row) {
unlink($location . $row['User_Pic']); //Delete old pic
}
$name=$_FILES['user_img']['name'];
$temp_name=$_FILES['user_img']['tmp_name'];
move_uploaded_file($temp_name,$location.$name);
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username',User_Pic='$name' where Id='$update_id'";
} else { //User did not upload image
if ($row) {
echo $location . $row['User_Pic']; //Echo current image path
}
$update_product = "update user set FullName='$fullname',Designation='$designation',UserName='$username' where Id='$update_id'";
}
$run_product = mysqli_query($con, $update_product);
if ($run_product){
echo"<scripy>alert('Update Successful')</script>";
echo "<script>window.open('user_manage.php','_self') </script>";
}
}
?>
Please note that the code shown here does not change the filename when storing the files on the server. This will cause problems when two person upload pictures with same filename. You need to implement an appropriate solution for that.

Related

PHP doesn't post to DB from data entered in form?

I can't see the problem here. I enter data in my input cells and after submit it only refresh a page and do not post anything in the MySQL. I'm doing this by watching online tutorial which is old, so maybe there are some old methods, that could be a problem.
<?php
include "../db/connect.php";
if (isset($_POST['pavadinimas'])) {
$pavadinimas = mysqli_real_escape_string($con, $_POST['pavadinimas']);
$kaina = mysqli_real_escape_string($con, $_POST['kaina']);
$info = mysqli_real_escape_string($con, $_POST['info']);
$gamintojas = mysqli_real_escape_string($con, $_POST['gamintojas']);
$gamintojas = mysqli_real_escape_string($con, $_POST['atmintis']);
$tipas = mysqli_real_escape_string($con, $_POST['tipas']);
$kiekis = mysqli_real_escape_string($con, $_POST['kiekis']);
// See if that product name is an identical match to another product in the system
$sql = mysqli_query($con, "SELECT id FROM prekes WHERE pavadinimas='$pavadinimas' LIMIT 1");
$productMatch = mysqli_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo '<script type="text/javascript">alert("KLAIDA! Bandėte įkelti prekę, kurios pavadinimas jau yra įrašytas duomenų bazėje.");</script>';
exit();
}
// Add this product into the database now
$sql = mysqli_query($con, "INSERT INTO prekes (pavadinimas, kaina, info, gamintojas, atmintis, tipas, kiekis, laikas)
VALUES('$pavadinimas','$kaina','$info','$gamintojas','$atmintis','$tipas','$kiekis',now())") or die (mysqli_error($con));
$pid = mysqli_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
header("location: itemList.php");
exit();
}
?>
There was just a dumb mistake. In html SUBMIT button name was set to 'button', not submit, so it didn't post it to the database.
and this
if (isset($_POST['pavadinimas']))
should have been this
if (isset($_POST['submit']))

How to upload and insert multiple images in PHP and mysql database

I am a beginner in PHP. I encoded some images in a base64String. All images are successfully decoding in the specified folder. My problem is am only able to record one image/path in the database. Somebody help me to come up with the PHP to insert all images paths in one row in the database.
here is the php code
<?PHP
if(isset($_POST['image']))
{
$image = $_POST['image'];
$identity = $_POST['id'];
$username = $_POST['username'];
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = rand(1000000, 10000000000);
$id2=rand(1000000, 10000000000);
$upload_folder = "upload";
$id="$id$id2";
$path = "$upload_folder/$id.jpeg";
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
$sql = "UPDATE apartment SET Image_path = '$path' WHERE apart_username
='$username' AND id = '$identity'";
mysqli_query($conn, $sql);
}
else{
echo "uploaded_failed";
}
exit;
}
else{
echo "images_not_in";
exit;
}
?>
You need some sort of loop...all I did in the example below was instead of making a single variable called image I made a array called $imagesArr. And I added a foreach loop on the imagesArr so it will run the code you wrote for each image you input into that array. I also killed the exit at the end as that would stop the loop. That should work
<?PHP
if(isset($_POST['image']))
{
//$image = $_POST['image']; - I commented this out
$imagesArr = array('image1.jpeg','image2.jpeg','image3.jpeg'); //etc. put all of your images here into this array
$identity = $_POST['id'];
$username = $_POST['username'];
foreach ($imagesArr as $key => $image) {
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = rand(1000000, 10000000000);
$id2=rand(1000000, 10000000000);
$upload_folder = "upload";
$id="$id$id2";
$path = "$upload_folder/$id.jpeg";
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
$sql = "UPDATE apartment SET Image_path = '$path' WHERE apart_username
='$username' AND id = '$identity'";
mysqli_query($conn, $sql);
}
else{
echo "uploaded_failed";
}
}
else{
echo "images_not_in";
}
}

PHP if in POST load only the first if

I have this code :
if(isset($_POST['remove'])){
$con = mysqli_connect(".","","","");
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
It is working, but I want it to do something like this
if(isset($_POST['remove'])){
$con = mysqli_connect("","","","");
while($row = mysqli_fetch_assoc($q)){
if($row['picture'] == ""){
echo "<div class='notemarg'> No pictures to delete</div>";
} else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}
}
This means that the picture from database will be removed only if there IS any picture.. if not, then it will display that message "No pictures to delete" ... but it does not work.. it still shows that error message that there is no picture even though there is no blank row in database and so it does not delete the information in row either...
Where is problem?
BTW: first code works fine... and it works even if there is nothing in database so it kinda does not make sense that the "profile picture has been removed." is being displayed...
Try this instead:
$con = mysqli_connect("","","","");
if(isset($_POST['remove'])){
$q = mysqli_query($con, "SELECT picutre FROM members where username = '". $_SESSION['username']. "'");
$row = mysqli_fetch_assoc($q);
if( empty($row['picture'])){
echo "<div class='notemarg'> No pictures to delete</div>";
}
else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}
You need the mysqli_query statement:
$con = mysqli_connect("","","","");
if(isset($_POST['remove'])){
$q = mysqli_query($con,"SELECT IFNULL(picture,'') AS picture
FROM members
WHERE username = '".$_SESSION['username']."'");
$row = mysqli_fetch_assoc($q);
if( empty($row['picture'])){
echo "<div class='notemarg'> No pictures to delete</div>";
}
else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}

PHP copy and unlink being ignored

This code runs when a user hits a delete button on my form. I am trying to copy a file, $picfile, from "/pics/" to "/pics/deletedrecordpics/" and then delete the orginal. Finally, delete the record from the database. Deleting the record from the databse works, but copying the file and deleting the original does nothing. There are no errors in the error log, so I am really confused as to why this code isn't running as I think it should.
if ($allowdelete==true && $thepassword == $password)
{
//delete record that delete was set to by button
//$sql = ("DELETE FROM $table WHERE id=$id");
$sql = ("select picfile,title,author from $table where id=$delete");
$file=mysql_query($sql);
$resrow = mysql_fetch_row($file);
$picfile = $resrow[0];
$title = $resrow[1];
$author = $resrow[2];
if (file_exists("/pics".$picfile)){
copy("/pics/".$picfile,"/pics/deletedrecordpics/".$author."-".$title."-".$picfile);
unlink("/pics/".$picfile);
echo $available = "image is available.";
$sql = ("DELETE FROM $table WHERE id=$delete");
$result = mysql_query($sql);
if ($result){
echo "Your Picture has been removed from our system.";
Die($available);
}
else{
echo "There was an error in removing your picture.";
$Delete = "";
Die();
}
}
else{
echo $available = "image is not available.";
}
}
The weird part is a have almost the same code in a delete button on my control panel located in "/adminpanel" and it works perfectly. The code for that is the same except I use $id instead $delete and "../" before all the "pics/" because it's in the adminpanel folder. The permissions are right and the folder exists because the code works with that page. And I know $delete is getting set because the record gets deleted from the database. I know picfile, author and title are getting set because I appended them to the print statement and they were all right. Really confused. Any ideas?
Here is the code for the working page
q = ("select picfile,title,author from $table where id=$id");
$file=mysql_query($q);
$resrow = mysql_fetch_row($file);
$picfile = $resrow[0];
$title = $resrow[1];
$author = $resrow[2];
copy("../pics/".$picfile,"../pics/deletedrecordpics/".$author." - ".$title." - ".$picfile);
unlink("../pics/".$picfile);
$file=mysql_query($q);
$q = ("DELETE FROM $table WHERE id=$id");
$file=mysql_query($q);
why is this line repeated twice $file=mysql_query($q); ?
Try this
$file_path = $_SERVER["DOCUMENT_ROOT"]."/pics/";
if (file_exists($file_path.$picfile))
{
copy($file_path.$picfile, $file_path."/deletedrecordpics/".$author."-".$title."-".$picfile);
unlink($file_path.$picfile);
}
else
{
echo "File not found!!!!!!!!";
}

How to delete an image using PHP & MySQL?

I was wondering if some one can give me an example on how to delete an image using PHP & MySQL?
The image is stored in a folder name thumbs and another named images and the image name is stored in a mysql database.
Delete the file:
unlink("thumbs/imagename");
unlink("images/imagename");
Remove from database
$sql="DELETE FROM tablename WHERE name='imagename'"
$result=mysql_query($sql);
Assuming name is the the name of the field in the database holding the image name, and imagename is the image's name.
All together in code:
$imgName='sample.jpg';
$dbFieldName='name';
$dbTableName='imageTable';
unlink("thumbs/$imgName");
unlink("images/$imgName");
$sql="DELETE FROM $dbTableName WHERE $dbFieldName='$imgName'";
mysql_query($sql);
try this code :
$img_dir = 'image_directory_name/';
$img_thmb = 'thumbnail_directory_name/';// if you had thumbnails
$image_name = $row['image_name'];//assume that this is the image_name field from your database
//unlink function return bool so you can use it as conditon
if(unlink($img_dir.$image_name) && unlink($img_thmb.$image_name)){
//assume that variable $image_id is queried from the database where your image record your about to delete is...
$sql = "DELETE FROM table WHERE image_id = '".$image_id."'";
$qry = mysql_query($sql);
}else{
echo 'ERROR: unable to delete image file!';
}
Are you looking for actual code or just the idea behind it?
You'll need to query the db to find out the name of the file being deleted and then simply use unlink to delete the file in question.
so here's some quick code to get you started
<?php
$thumb_dir = "path/to/thumbs/";
$img_dir = "path/to/images/";
/* query your db to get the desired image
I'm guessing you're using a form to delete the image?
if so use something like $image = $_POST['your_variable'] to get the image
and query your db */
// once you confirm that the file exists in the db check to see if the image
// is actually on the server
if(file_exists($thumb_dir . $image . '.jpg')){
if (unlink($thumb_dir . $image . '.jpg') && unlink($img_dir . $image . '.jpg'))
//it's better to use the ID rather than the name of the file to delete it from db
mysql_query("DELETE FROM table WHERE name='".$image."'") or die(mysql_error());
}
?>
if(!empty($_GET['pid']) && $_GET['act']=="del")
{
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".$_DIR['site']['adminurl']."mservices".$atend."suc".$_DELIM."3".$baratend);
exit();
}
}
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".

Categories