2014-03-03 50 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

,这个回答是不正确的 –