gpt4 book ai didi

php - 复杂的 PDO MYSQL 查询不起作用

转载 作者:行者123 更新时间:2023-11-30 01:23:39 25 4
gpt4 key购买 nike

我编写了一个 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();
}

编辑:不用担心 include 语句、$config[]-array 和类变量。这一切也都正常工作。已经测试了它们的值。

最佳答案

更改这部分:

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

致:

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

因为根据PHP Manual: PDOStatement::bindParam

Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

关于php - 复杂的 PDO MYSQL 查询不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18260076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com