I'm trying to implement a method to update users from the admin page through a form.
I have a generic method update
because I'm updating my own MVC framework.
public function update()
{
$tableName = $this->tableName();
$attributes = $this->attributes();
$params = array_map(fn($attr) => ":$attr", $attributes);
$paramsArray = array_combine($attributes, $params);
$list = [];
foreach ($paramsArray as $key => $value) {
$list[] = "$key=$value";
}
$primaryKey = $this->primaryKey();
$primaryValue = $this->{$primaryKey};
try {
$statement = self::prepare("UPDATE $tableName SET " . implode(', ', $list) . " WHERE $primaryKey = $primaryValue");
foreach ($attributes as $attribute) {
$statement->bindValue(":$attribute", $this->{$attribute});
}
$statement->execute();
return true;
} catch (\PDOException $e) {
echo "Check Input Error: " . $e->getMessage() . "</br>";
}
}
So, this method (with my user) give me this statement :
'UPDATE users SET firstname=:firstname, lastname=:lastname, email=:email, password=:password, status=:status, type=:type WHERE id = 10'
.
I don't catch any PDOException, but nothing change in my database.
I setted PDO attributes like that :
pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
Things I checked :
- I dumped this part
$this->{$attribute}
in my foreach and the values I'm getting are fine. - I've tried to use the statement above directly in PHPMyAdmin and replacing the bind values by the real values and everything works fine.
- I also tried to change the statement to create a mysql query error and I had one.
Maybe I'm missing something from the whole update process but I have a save
method for database INSERT
that use kind of the same logic and it works fine.