duan7264 2012-03-06 18:34
浏览 330
已采纳

将特殊字符插入Postgresql数据库

I have a php script which returns some values with special characters, especially single quotes(') and the 'at sign'(@). The values that contain these characters are not inserted into the database. I saw a post in doing this on mysql database at (http://stackoverflow.com/questions/2584066/php-how-to-insert-special-characters-into-a-database). My question then is how can it be done in Postgresql database.

See below the php code:

<?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();

?>
  • 写回答

2条回答 默认 最新

  • douzhao6584 2012-03-06 18:38
    关注

    You have a few of options:

    • You could wrap dynamic data pg_escape_string() (and related functions for other types) to properly encode special characters. This will require the least amount of change to the code you've posted.

    • You could use prepared statements and bind your dynamic data as parameters. See the docs for pg_prepare() for examples on how to do this. Prepared statements are the recommended way to protect against SQL Injection.

    • You could use PDO with parameterized queries. This gives you the safety and performance benefits of parameterized queries plus a universal database abstraction layer.

    The last option is preferred.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发