Reputation: 119
I am trying to allow users to update a table that has an image file-upload input. Only the filename is stored in the database, such as image.jpg. My problem is that if the user chooses not to change the image it clears what is in the database since it sends a null value. How do I only update the IMAGE field if input file is not null?
// prepare and bind
$stmt = $conn->prepare("UPDATE News SET
TITLE=?,
CONTENT=?,
IMAGE=?
WHERE ID=?");
$stmt->bind_param("sssd", $title, $content, $image, $id);
Upvotes: 1
Views: 1373
Reputation: 74220
It couldn't be any simpler than using a conditional statement:
The logic:
if(condition){ do something } else{ do something else }
Which you could use in conjunction with your $_FILES
array and as an example:
if(!empty($_FILES['file'])){
// execute SQL
}
else{
// do something else
}
Upvotes: 1
Reputation: 333
To work for all cases, adding to Don Djoe's answer:
if (isset($image) && !empty($image))
{
// your code
$stmt = $conn->prepare("UPDATE News SET
TITLE=?,
CONTENT=?,
IMAGE=?
WHERE ID=?");
$stmt->bind_param("sssd", $title, $content, $image, $id);
}
else
{
// your code
$stmt = $conn->prepare("UPDATE News SET
TITLE=?,
CONTENT=?
WHERE ID=?");
$stmt->bind_param("ssd", $title, $content, $id);
}
Upvotes: 0
Reputation: 705
Not sure if this is what you are looking for, as you might want something more complicated
if (isset($image) && !empty($image))
{
// your code
$stmt = $conn->prepare("UPDATE News SET
TITLE=?,
CONTENT=?,
IMAGE=?
WHERE ID=?");
$stmt->bind_param("sssd", $title, $content, $image, $id);
}
Upvotes: 0