0

我编写了一个 php 函数,它允许您使用任何字符串值(一个或多个)更新任何表中的任何条目。PDO 不会抛出任何错误,尽管脚本似乎不起作用!我已经多次检查数据库、表和字段的名称。都是正确的。这是我的函数中唯一不起作用的查询。我相信它与传递给 SQL 语句和 PDO->bindParam() 函数的数组有关。

代码:

public function updateTableDetail($table, $id, $params) {

    include($this->doc_root . 'config/config.php');

    if (is_array($params)) {
        foreach ($params as $param) {
            $param = Utilities::escapeString($param);
        }
    } else {
        throw new InvalidInputException(InputErrors::NOTANARRAY);
    }
    if (is_nan($id)) throw new InvalidInputException(InputErrors::NOTANUMBER);
    $table = Utilities::escapeString($table);

    $sql = "UPDATE " . $table . "
            SET " . $config['table_field_updated'] . " = :updated";
    while (current($params)) {
        $sql .= "," . key($params) . " = :" . key($params);
        next($params);
    }
    reset($params);
    $sql .= " WHERE id = :id 
             AND " . $config['userId'] . " = :userId";

    if ($this->serverConnector == null) {
        $this->serverConnector = new ServerConnector();
    }
    if ($this->db == null) {
        $this->db = $this->serverConnector->openConnectionOnUserDb($this->dbname);
    }
    $stmt = $this->db->prepare($sql);
    $updated = date("Y-m-d H:i:s");
    $stmt->bindParam(':updated',$updated);
    $stmt->bindParam(':id',$id);
    $stmt->bindParam(':userId',$this->userId);
    while ($param = current($params)) {
        $stmt->bindParam(":".key($params),$param);
        next($params);
    }
    reset($params);
    $stmt->execute();
}

编辑:不要担心包含语句、$config[]-array 和类变量。这一切都在工作。已经测试了他们的价值观。

4

1 回答 1

0

更改此部分:

while ($param = current($params)) {
        $stmt->bindParam(":".key($params),$param);
        next($params);
    }

到:

foreach($params as $key => &value){
$stmt->bindParam(":$key",$value);
}

因为根据PHP 手册:PDOStatement::bindParam

将 PHP 变量绑定到用于准备语句的 SQL 语句中相应的命名或问号占位符。与 PDOStatement::bindValue() 不同,该变量被绑定为引用,并且只会在调用 PDOStatement::execute() 时进行评估。

于 2013-08-15T19:25:46.770 回答