我正在使用以下脚本从html表单中获取数据并存储在Postgres数据库中。有这个pg_escape_string函数,它将表单中的值存储到php变量中。在整个网络中搜索,我发现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>
答案 0 :(得分:6)
请考虑以下代码:
$sql = "INSERT INTO airports (name) VALUES ('$name')";
现在假设$name
是"Chicago O'Hare"
。当您进行字符串插值时,您将获得以下SQL代码:
INSERT INTO airports (name) VALUES ('Chicago O'Hare')
格式不正确,因为撇号被解释为 SQL引号,您的查询将会出错。
Worse things也可能发生。事实上,SQL注入被MITER评为#1 Most Dangerous Software Error of 2011。
但是你永远不应该使用字符串插值来创建SQL查询。请改用queries with parameters。
$sql = 'INSERT INTO airports (name) VALUES ($1)';
$result = pg_query_params($db, $sql, array("Chicago O'Hare"));
答案 1 :(得分:2)