[英]update query php postgres failing for no reason
我在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()轉義用於查詢PostgreSQL數據庫的文字。 它以PostgreSQL格式返回轉義文字。 pg_escape_literal()在數據前后添加引號。 建議使用此函數而不是
pg_escape_string()
。
您永遠不要使用addslashes
來引用數據庫的字符串:
我們強烈推薦使用DBMS特定的逃生功能(如
mysqli_real_escape_string()
為MySQL或pg_escape_string()
PostgreSQL的)
您應該這樣做:
$newq = sprintf("update purchase_info set ... comments=%s where id=%d", ..., pg_escape_literal($comm), $id);
我假設id
實際上也是一個數字。
假設您確實要向SQL查詢中注入參數,則正確的代碼將是:
$newq=sprintf("update purchase_info set ... comments='%s' where id='%s'",
pg_escape_string($comm), pg_escape_string($id));
// DO NOT USE to addslashes, it is not correct
$result=pg_query($link, $newq);
注意格式字符串中%s的單引號。 另外,如果id是整數,最好使用%d(不帶引號)而不是'%s'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.