这是我的代码更新数据。如果没有选择图像,如何使用旧图像?
当有人更新其个人资料但未选择要更新的图片时,该个人资料页面应该保留旧图像。
<?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>";
}
}
?>
答案 0 :(得分:0)
首先,您需要从数据库中获取现有的用户详细信息,并检查用户是否已有个人资料图片。
接下来,如果用户上传了新图片,则可以使用unlink()
功能删除旧的个人资料图片。如果用户没有上传新图片,您可以保留旧图片。
请参阅下面的代码。
<?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>";
}
}
?>
请注意,在服务器上存储文件时,此处显示的代码不会更改文件名。当两个人上传具有相同文件名的图片时,这将导致问题。您需要为此实施适当的解决方案。