2014-03-03 51 views
0

我知道這個話題已經在stackoverflow中討論了很多,但是我已經閱讀了所有主題,但是我找不到解決方案。使用pdo參數更新sql數據庫 - 沒有錯誤 - 什麼都不做

我有這個函數應該更新mysql數據庫。它只是不做任何事情,並沒有顯示任何錯誤。正如你所見,我使用PDO。我在stackoverflow中看到了很多類似於我的問題,並嘗試了他們的解決方案,但似乎都沒有工作。

我已經檢查過,我傳遞給這個函數的所有變量都到達並且正確。

public function updateValues($coreID, $table, $name, $time){ 
    if ($this->databaseConnection()) {   
    $query_edit_user_name = $this->db_connection->prepare("UPDATE :tableT SET time = :timeT, name = :nameT WHERE id = :coreID"); 
    $query_edit_user_name->bindValue(':coreID', trim($coreID), PDO::PARAM_STR); 
    $query_edit_user_name->bindValue(':tableT', trim($table), PDO::PARAM_STR); 
    $query_edit_user_name->bindValue(':nameT', trim($name), PDO::PARAM_STR); 
    $query_edit_user_name->bindValue(':timeT', trim($time), PDO::PARAM_INT); 
    $query_edit_user_name->execute(); 
} 
} 

我一直試圖添加'或'到不同的行名稱或值,但沒有奏效。 「有效」的唯一方法是如果沒有單個PDO參數:

$query_edit_user_name = $this->db_connection->prepare("UPDATE table1 SET time = '55', name = 'name1' WHERE id = 'core2'"); 

任何想法?

回答

3

不能使用綁定值或參數作爲表名稱。

$query_edit_user_name = $this->db_connection->prepare("UPDATE :tableT SET time... 
                   ^^^^^^^ 

試試這個:

public function updateValues($coreID, $table, $name, $time){ 
if ($this->databaseConnection()) { 
$query_edit_user_name = $this->db_connection->prepare("UPDATE `$table` SET time = :timeT, name = :nameT WHERE id = :coreID"); 
$query_edit_user_name->bindValue(':coreID', trim($coreID), PDO::PARAM_STR); 
$query_edit_user_name->bindValue(':nameT', trim($name), PDO::PARAM_STR); 
$query_edit_user_name->bindValue(':timeT', trim($time), PDO::PARAM_INT); 
$query_edit_user_name->execute(); 

正如已指出了意見,動態表名是開放的一個可能的注入,這取決於所在的表的名稱源自。

$table = str_replace(array('\\',"\0" ,'`'), '', $table); 

或者,使用白名單方法:

$allowed = array('table1', 'table2'); 
if (in_array($table, $allowed)) { 
    // prepare and execute query 
} 
+0

你可能想在這裏給更多的上下文,但這是

無論哪種,喜歡的東西準備語句之前逃脫表名正確。上下文是準備好的陳述如何實際工作的邏輯思想運動。那麼,MySQL怎麼可能「準備」一個陳述,而不知道它將會用到哪些數據庫對象呢? –

+1

@MikeBrant @你不能要求對這個問題的每一個答案,每天問兩次,這個問題是關於準備好的陳述的綜合指南。 –

+0

,這個回答是不正確的 –