Reputation: 2823
I have a update function that for now updates the required changes to MySQL database when I run index.php.
This is updating my password buy not the name field, ive been over the code and can not work out why. Any help is greatly appreciated.
Index that tells what id and fields to update with entered data
<?php
require_once 'core/init.php';
$userInsert = DB::getInstance()->update('users', 1, array(
'password' => 'newpass',
'name' => 'Ben'
));
Function in different php that updated database
public function update($table, $id, $fields) {
$set = '';
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)) {
$set .= ',';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} = 'newpassword' WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
I believe it to be a small error or mistype but I can not see the problem.
As you can see bellow the password field has been changed but the name has not
Upvotes: 1
Views: 13064
Reputation: 1
private function update($table, $primaryKey, $fields) {
$query = 'UPDATE `' . $this->table . '` SET ';
foreach ($fields as $key => $value) {
$query .= '`' . $key . '` = :' . $key . ',';
}
$query = rtrim($query, ',');
$query .= ' WHERE `' . $this->primaryKey . '` = :primaryKey';
$fields['primaryKey'] = $fields['id'];
$this->query($query, $fields);
}
An example of an update function. Attention mine is inside a class and the query is another function and passes as an object.
Upvotes: 0
Reputation: 1529
Simply use of prepare
and execute
in PDO:
$sql = 'UPDATE '. $table .' SET username = :username, password = :password WHERE id = '. $id;
$sth = $dbh->prepare($sql);
$sth->execute(array(
':username' => 'ben',
':password' => 'newpassword'
));
Upvotes: 1
Reputation: 1087
public function update($table, $id, $fields) {
$set = '';
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = \"{$value}\"";
if($x < count($fields)) {
$set .= ',';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
Upvotes: 4