【发布时间】:2012-03-26 07:51:37
【问题描述】:
这是 w3schools.org 上的示例:
HTML 表单:
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
文件插入.php:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
我已阅读此处的其他问题,但找不到直接答案,因为大多数问题要复杂得多。
我查看了 How can I prevent SQL injection in PHP?,但对如何修改它有点困惑:
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute(array(':column' => $unsafeValue));
假设我使用上面的 HTML 表单并想将字段 'firstname' 中的数据插入到数据库中,它应该是这样的吗?还是我应该修改column?:
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute(array(':column' => $firstname));
【问题讨论】:
-
那么,你到底有什么问题?
-
我怎样才能使这种方法安全?