SteveMills04
SteveMills04

Reputation: 119

UPDATE SQL, only UPDATE image if not null

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

Answers (3)

Funk Forty Niner
Funk Forty Niner

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

Afaan Bilal
Afaan Bilal

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

Don Djoe
Don Djoe

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

Related Questions