How to enter specific values ​​in input fields even if some of them are empty?
P粉418854048
P粉418854048 2024-03-20 09:52:58
0
1
367

How to change one or more selection values? If I enter a value it works. Still, if I enter two values ​​in both input fields, it doesn't work, showing the following error.

Error updating record: There is an error in your SQL syntax; check The manual corresponding to your MariaDB server version Line 1 Syntax used near 'nat = 'saf' WHERE id = '16''

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();
}

P粉418854048
P粉418854048

reply all(1)
P粉798010441

@m-eriksson 评论的实施方法:

$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);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!