2012-03-06 286 views
2

我有一個php腳本,它返回一些帶有特殊字符的值,特別是單引號(')和'at符號'(@)。包含這些字符的值不會插入到數據庫中。我在MySQL數據庫中看到了一篇文章(http://stackoverflow.com/questions/2584066/php-how-to-insert-special-characters-into-a-database)。 我的問題是如何在Postgresql數據庫中完成。在Postgresql數據庫中插入特殊字符

請參見下面的PHP代碼:

<?php 
require 'table.php'; 


// Opens a connection to a PostgresSQL server 
$connection = pg_connect("dbname=postgis user=postgres password=local"); 


// Execute query   

foreach ($xml->item as $entry){ 
$georss = $entry->children($namespaces['georss']); 
list($lat, $lng) = explode(' ', (string)$georss->point); 
$query = "INSERT INTO geognews(title, link, author, latitude, longitude) VALUES ('" . $entry->title . "', '" . $entry->link . "', '" . $entry->children($namespaces['dc'])->creator . "', '" . $lat . "', '" . $lng . "')"; 

$result = pg_query($query); 
printf ("These values are inserted into the database - %s %s %s", $entry->title, $entry->link, $entry->children($namespaces['dc'])->creator, $lat, $lng); 
} 

pg_close(); 

?> 

回答

1

您有幾種選擇:

  • 你可以換動態數據pg_escape_string()(其它類型和相關功能),以正確編碼特殊字符。這需要對您發佈的代碼進行最少量的更改。

  • 您可以使用準備好的語句並將動態數據綁定爲參數。有關如何執行此操作的示例,請參閱pg_prepare()的文檔。編制的聲明是recommended way to protect against SQL Injection

  • 您可以使用帶參數化查詢的PDO。這爲您提供了參數化查詢以及通用數據庫抽象層的安全性和性能優勢。

最後的選項是首選。

2

使用pg_query_params()是迄今爲止最容易避免SQL注入的方法。因此引用'和其他有風險的東西。