2017-03-22 25 views
0

PDO更新查詢:與我要執行這樣的查詢括號

UPDATE users SET online_time = (online_time + 50) WHERE ID = 1 

我有一個問題,因爲online_time不更新,它是由0 取代在mysqli的一切都OK。 這是我在數據庫類更新功能的代碼(這是從互聯網上,而不是我的工作):

public function update($table, $data, $where) 
{ 
    ksort($data); 

    $fieldDetails = null; 
    foreach($data as $key => $value){ 
     $fieldDetails .= "$key=:$key, "; 
    } 
    $fieldDetails = rtrim($fieldDetails, ', '); 

    $sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where"); 

    foreach ($data as $key => $value){ 
     $sth->bindValue(":$key", $value); 
    } 
    $sth->execute(); 
} 

和代碼我試圖運行:

$set = ['online_time' => "(online_time + $t)"]; 
$where = 'ID = '. $id; 
$this->db->update('users', $set, $where); 

這可能是什麼問題更新功能,但我不知道什麼:/

+0

你收到任何錯誤? – hassan

+0

但是你會遇到一個問題,因爲在你的foreach循環中:''$ key =:$ key,「'所以在添加你的'$ set'變量後,它會是這樣的:'online_time = :(online_time + $ t )' – hassan

+0

'$ sth = $ this-> prepare(「UPDATE $ table SET $ fieldDetails WHERE $ where」);'這看起來很危險 –

回答

0

更新功能的第一個和最重要的問題是,它是prone to SQL injection

是的,它不適合用這樣的複雜表達式進行更新。

因此,對於這個特定的查詢簡單地避免這種功能和運行只是一個原料預處理語句

$sth = $db->prepare("UPDATE users SET online_time = online_time + ? WHERE ID = ?"); 
$sth->execute([$t, $id]);