0

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();
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
  • What are you trying to achieve? – samayo Apr 30 '22 at 17:22
  • **Warning!** You're open to [SQL injection attacks](https://owasp.org/www-community/attacks/SQL_Injection)! Read [how to prevent SQL injection in PHP](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) by using prepared statements with bound parameters instead of injecting variables directly into your queries. It's not just about security. If your data contains, for example, a single quote `'`, your query will break. – M. Eriksson Apr 30 '22 at 17:24
  • I'm not trying to get it, I'm trying to modify existing users using a form. If I want to change only his name and other data and I would like to go with a single value but also when there are several values – Adrian G Apr 30 '22 at 17:24
  • If you echo the final SQL query before executing it, you should see the issue. You're missing `,` between setting the columns. Your code will produce `SET nume = 'x'nat='y'` when it should be `SET nume='x',nat='y'` (notice the comma). That's why it's working with one but not multiple columns. – M. Eriksson Apr 30 '22 at 17:28
  • I don't know where to put a comma in my code Where exactly please? – Adrian G Apr 30 '22 at 17:35

1 Answers1

0

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);
}
  • Show me this error : Fatal error: Uncaught Error: Using $this when not in object context i. I tried with self:: and not working – Adrian G Apr 30 '22 at 19:57