我正在使用以下腳本,它從一個html表單中獲取數據並存儲在Postgres數據庫中。有這個pg_escape_string函數,它將表單中的值存儲到php變量中。在整個網絡搜索中,我發現pg_escape_string轉義了一個字符串插入到數據庫中。我對此並不十分清楚。它實際上逃脫了什麼?當它說一個字符串被轉義時實際發生了什麼?pg_escape_string究竟幹什麼?
<html>
<head></head>
<body>
<?php
if ($_POST['submit']) {
// attempt a connection
$dbh = pg_connect("host=localhost dbname=test user=postgres");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// escape strings in input data
$code = pg_escape_string($_POST['ccode']);
$name = pg_escape_string($_POST['cname']);
// execute query
$sql = "INSERT INTO Countries (CountryID, CountryName) VALUES('$code', '$name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Country code: <br> <input type="text" name="ccode" size="2">
<p>
Country name: <br> <input type="text" name="cname">
<p>
<input type="submit" name="submit">
</form>
</body>
</html>
這真是太舊了,但對於任何後來遇到此問題的人來說,pg_escape_string()是防禦SQL注入的一種防禦措施,但並未阻止它。使用準備好的語句更好。 (http://stackoverflow.com/questions/732561/why-is-using-a-mysql-prepared-statement-more-secure-than-using-the-common-escape) – pandubear