php - 更新查询 php postgres 无故失败

标签 php postgresql postgresql-8.4

我在 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 or pg_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/

相关文章:

php - 将文件从 Android 上传到 DJango。 Request.FILES 总是空的

php - 如何通过函数路由每个 mysql 查询?

node.js - Redis与Postgresql同步(在线用户状态)

sql - 统计每周比赛的奖牌数

postgresql - 如何使用 psycopg2 将 postgresql 的结果保存到 csv/excel 文件?

php - 为什么我的透明 div 上的链接在 IE 中变得不可点击?

php - 如何调试 webhook POST?

postgresql - 使用 INSERT INTO 时的错误消息

sql - Rails 包含条件不从左表返回所有结果的查询

sql - 以正确的方式在多列的大表中查找重复记录