【发布时间】:2016-03-27 20:41:59
【问题描述】:
我有一个这样的 SQL $query;
UPDATE `tags` SET `tags.name` = :name,
`tags.slug` = :slug,
`tags.date_published` = :date_published,
`tags.meta_title` = :meta_title,
`tags.meta_description` = :meta_description,
`tags.meta_keywords` = :meta_keywords
WHERE `tags.id` = :id
还有我的 $values 数组;
Array
(
[:name] => iphone
[:slug] => iphone
[:date_published] => 2016-03-27
[:meta_title] => iphone Yazıları
[:meta_description] => iphone hakkında son gelişmeler ve faydalı bilgiler.
[:meta_keywords] => iphone yazıları, iphone hakkında bilgiler, iphone haberleri
[:id] => 24
)
我正在尝试使用 PDO 的准备功能更新一行;
$sth = $this->db->prepare($query);
$sth->execute($values);
echo "affected rows: ".$sth->rowCount(); // prints 0
return $sth->rowCount() ? true : false;
我没有收到任何错误,但执行查询后行不受影响。我的错在哪里?
编辑: 我正在创建这样的值数组;
$params = array(
"id", "name", "slug", "date_published",
"meta_title", "meta_description", "meta_keywords");
$values = array();
foreach ($params as $key) {
@$values[$key] = $_POST[$key];
}
这就是我创建查询的方式;
$query = "UPDATE `$table` SET";
$values = array();
/* Add field names and placeholders to query. */
foreach ($params as $key => $value) {
$query .= " `{$table}.{$key}` = :" . $key . ",";
$values[":" . $key] = $value;
}
/* Remove last comma. */
$query = substr($query, 0, -1);
/* Build where condition. */
if ($cond) {
$query .= " WHERE ";
foreach ($cond as $key => $value) {
$query .= " `{$table}.{$key}` = :" . $key . ",";
$values[":" . $key] = $value;
}
/* Remove last comma. */
$query = substr($query, 0, -1);
}
【问题讨论】:
-
你的数组看起来很奇怪。你能在你创建这个数组的地方展示你的 PHP 代码吗?
-
看起来您正在使用 phpMyAdmin。您是否确认(在 phpMyAdmin 中)这些行确实没有受到影响?这将帮助您确定问题出在您的查询上,还是出在
rowCount()上。 -
如果要更新到相同的数据,则不会发生更新,因此行数为 0。
-
@low_rents 我添加了创建数组的方式。
-
@alexw 是的,我检查了行,它们没有受到影响。 :(