Tôi đang sử dụng tập lệnh sau để lấy dữ liệu từ biểu mẫu html và lưu trữ trong DB Postgres. Có hàm pg_escape_string này lưu trữ giá trị từ biểu mẫu tới biến php. Tìm kiếm trên web trong suốt, tôi thấy rằng pg_escape_string thoát chuỗi để chèn vào cơ sở dữ liệu. Tôi không rõ ràng về điều này. Nó thực sự trốn thoát là gì? Điều gì thực sự xảy ra khi nó nói rằng một chuỗi được thoát ra?Whats pg_escape_string chính xác làm gì?
<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>
Điều này thực sự cũ, nhưng đối với bất kỳ ai gặp vấn đề này sau, pg_escape_string() là một biện pháp phòng chống SQL injection, nhưng không ngăn chặn nó. Sử dụng báo cáo chuẩn bị tốt hơn. (http://stackoverflow.com/questions/732561/why-is-using-a-mysql-prepared-statement-more-secure-than-using-the-common-escape) – pandubear