PHP PDO更新表

时间:2018-01-27 01:49:30

标签: php oop pdo

所以我正在学习Udemy课程,然后导师做了这个功能

public function update($table, $user_id, $fields = array()){

  $columns = '';
  $i       = 1;

  foreach($fields as $name => $value){

    $columns .= "'{$name}' = :{$name}";
    if($i < count($fields)){
        $columns .= ', ';
    }
    $i++;
  }

  $sql = "UPDATE {$table} SET {$columns} WHERE 'user_id' = {$user_id}";
  if($stmt = $this->pdo->prepare($sql)){
    foreach($fields as $key => $value){
        $stmt->bindValue(':'.$key, $value);
    }
    $stmt->execute();
  }

}

我在他之后写了这么多次,它似乎永远不会起作用,有人会向我解释代码有什么问题吗?

2 个答案:

答案 0 :(得分:0)

这里

$sql = "UPDATE {$table} SET {$columns} WHERE 'user_id' = {$user_id}";

表名周围的'应该是反引号,而不是单引号:

$sql = "UPDATE {$table} SET {$columns} WHERE `user_id` = {$user_id}";

同样在这里:

$columns .= "`{$name}` = :{$name}";

答案 1 :(得分:0)

你应该用反引号替换单引号:

$columns .= "`{$name}` = :{$name}";

$sql = "UPDATE {$table} SET {$columns} WHERE `user_id` = {$user_id}";

只是建议:您可以使用数组来构建columns子句,只需传递execute即可直接bindValue而不需要任何$fields阵列:

function update($table, $user_id, $fields = array()) {

    $columns = [];

    foreach ($fields as $name => $value) {
        $columns[] = "`{$name}` = :{$name}";
    }

    $sql = sprintf('UPDATE %s SET %s WHERE `user_id` = %s'
            , $table
            , implode(', ', $columns)
            , $user_id
    );

    if ($stmt = $this->pdo->prepare($sql)) {
        $stmt->execute($fields);
    }
}