'How can I enter certain values ​in the input field even if some are empty?

How can I change one value or more values ​​of choice? If I enter a single value, it works. Still, if I enter two values ​​in two input fields, it doesn't work, showing me the following error.

Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'nat = 'saf' WHERE id = '16'' at line 1

if (isset($_POST['modifica'])) {
    $id = $_POST['id'];

    $semaphore = false;
    $sql = "UPDATE users SET ";
    $fields = array('nume', 'nat', 'email', 'telefon');
    foreach ($fields as $field) {
        if (isset($_POST[$field]) and !empty($_POST[$field])) {
            $var = ($_POST[$field]);
            $sql .= $field." = '$var'";
            $semaphore = true;
        }
    }

    if ($semaphore) {
        $sql .= " WHERE id = '$id'";
        ($sql);
    }
    
    if ($conn->query($sql) === true) {
        echo "Record updated successfully";
    } else {
        echo "Error updating record: ".$conn->error;
    }

    $conn->close();
}


Solution 1:[1]

An inplementatiom aproach of @m-eriksson comments:

$sql = "UPDATE users SET nume = :nume, nat = :nat, email = :email, telefon = :telefon";

$fields = array('nume', 'nat', 'email', 'telefon');

if(count($fields) > 0 ){ 
    $this->update($sql, $fields, $con)
    $semaphore = true;
}

public function update ($sql, $fields, $con)
{
    $update = $con->prepare($query);
    return $update->execute($fields);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1