【发布时间】:2018-12-07 08:41:23
【问题描述】:
我正在尝试编辑员工。如果以新名称形式上传新文件,我将删除旧文件。除了用旧图像更新外,这很好用。 我看了一些关于 Stackoverflow 问题的教程和示例,但它们无法解决我的问题。
我的问题是:
如果用户想保留旧图像,如何使用现有图像更新行 图片?
这是我的更新页面:
// This part select old image
try{
$id = $_REQUEST['update_id'];
$select_stmt = $pdo->prepare('SELECT * FROM employees WHERE id =:id');
$select_stmt->bindParam(':id',$id);
$select_stmt->execute();
$row = $select_stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
}catch(PDOException $e){
$e->getMessage();
}
}
if(isset($_REQUEST['btn_update'])){
try{
$name = $_REQUEST['name'];
$address = $_REQUEST['address'];
$salary = $_REQUEST['salary'];
// This part giving new name to image and validation.
$image_file = generatenewstring(12).$_FILES["image"]["name"];
$type = $_FILES["image"]["type"];
$size = $_FILES["image"]["size"];
$temp = $_FILES["image"]["tmp_name"];
$path="../images/ilanlar/".$image_file;
$directory="../images/ilanlar/";
if($image_file){
if($type=="image/jpg" || $type=='image/jpeg' || $type=='image/png' || $type=='image/gif'){
// Checking for image if exist we will delete this statment later on
if(!file_exists($path)){
if($size < 1000000){
// deleting old image
unlink($directory.$row['image']);
// uploading new image
move_uploaded_file($temp, "../images/ilanlar/" .$image_file);
}else{
$errorMsg = "Your File To large Please Upload 5MB Size";
}
}else{
$errorMsg = "File Already Exists...Check Upload Folder";
}
}else{
$errorMsg = "Upload JPG, JPEG, PNG & GIF File Formate.....CHECK FILE EXTENSION";
}
}else{
$image_file = $row['image'];
}
if(!isset($errorMsg)){
$stmt=$pdo->prepare('UPDATE employees SET
name=:name, address=:address, salary=:salary, image=:image
WHERE id=:id');
$stmt->bindParam(':name',$name);
$stmt->bindParam(':address',$address);
$stmt->bindParam(':salary',$salary);
$stmt->bindParam(':image',$image_file);
$stmt->bindParam(':id',$id);
//bind all parameters
if($stmt->execute()){
echo "File Update Successfully.......";
header("refresh:3;3.php");
}
}
}catch(PDOException $e){
echo $e->getMessage();
}
}
感谢您的帮助。
我尝试的代码太长,每次都要重新查询:
if ($image == 0) {
//query1
} else if ($image == 1) {
//query2
} else {
//query3
}
【问题讨论】:
-
你能告诉我们你到目前为止尝试了什么吗?
-
我尝试在 if 语句中做单独的查询,但那是一个很长的例子,所以我没有添加到问题中。
-
据我了解,如果
$image_file为空,您希望保留file列的值。在这种情况下,您可以在查询中执行类似image=COALESCE(:image,image)的操作。 -
如果没有上传新图像,我想保留旧文件,有没有
image=COALESCE(:image,image)的示例如何注入代码?以前从未听说过COALESCE()功能。谢谢 -
您的查询中现在有
image=:image,将其替换为image=COALESCE(:image,image)。 Documentation for COALESCE().