我在 PHP 中有这段代码,并使用 PostgreSQL 作为数据库。我从 GET 获取所有参数。通过打印检查它们。形成的查询在 Postgres 终端上执行,但在 PHP 脚本中失败。
这是一段代码。
<?php
$link = pg_connect("host=localhost dbname=postgres user=postgres password=password") or die('connection failed');
# Building the query
$newq=sprintf("update purchase_info set ....... comments=%s where id=%s",......,$comm,$id);
print $newq; // This query runs on the postgres terminal
$query=addslashes($newq); // to escape "" as one of my fields is comments
$result=pg_query($link,$newq);
if (!$result) {
echo "An error occured.\n";
}
pg_close($link);
?>
其他查询在同一脚本中运行。此 SQL 语句有大约 14 个字段正在更新。
听到什么地方出了问题。 感谢您的帮助!
最佳答案
你不应该使用 addslashes
来引用 PostgreSQL 的字符串,你应该使用 pg_escape_literal
:
pg_escape_literal() escapes a literal for querying the PostgreSQL database. It returns an escaped literal in the PostgreSQL format. pg_escape_literal() adds quotes before and after data. Use of this function is recommended instead of
pg_escape_string()
.
你不应该使用 addslashes
为数据库引用字符串:
It's highly recommended to use DBMS specific escape function (e.g.
mysqli_real_escape_string()
for MySQL orpg_escape_string()
for PostgreSQL)
你应该这样做:
$newq = sprintf("update purchase_info set ... comments=%s where id=%d", ..., pg_escape_literal($comm), $id);
我假设 id
实际上也是一个数字。
关于php - 更新查询 php postgres 无故失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10236589/