Is this a secure method to insert form data into a MySQL database?

Possible Duplicate:
Best way to stop SQL Injection in PHP

This is the example on w3schools.org:

HTML form:

<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>

insert.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)
?>

I've read through other threads on here, but couldn't find a direct answer, as most were much more complicated.

EDIT: I looked at best way to stop sql-injection in php, but I'm a bit confused on how to modify this:

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array(':column' => $unsafeValue));

Assuming I used the html form above and wanted to insert the data from field 'firstname' into the database, should it look like this? Or am I supposed to modify column ?:

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array(':column' => $firstname));

The example you provided inserts the post vars into the database without first analyzing them for evil user input. Use type casting, escaping/filter functions, prepared statements etc. before using them to interact with your DB.

A general rule to go by is to never trust user input. EVER!

Check out: Best way to stop SQL Injection in PHP

Update: In response to your question, here is how you'd handle the entire form using PDO prepared statements.

$stmt = $db->prepare('INSERT INTO Persons (FirstName, LastName, Age) VALUES (:first_name, :last_name, :age)');

$stmt->execute(array(':first_name' => $first_name,':last_name' => $last_name, ':age' => $age));

If you just want to insert one column in the record like you asked, the syntax would be:

$stmt = $db->prepare('INSERT INTO Persons (FirstName) VALUES (:first_name)');

$stmt->execute(':first_name', $first_name);

NO.

That is HIGHLY vulnerable to sql injection attacks.

Instead of using mysql_real_escape_string , i suggest using prepared statements.


使用mysql_real_escape_string。

链接地址: http://www.djcxy.com/p/16728.html

上一篇: PHP的MySQL注入示例?

下一篇: 这是一种将表单数据插入MySQL数据库的安全方法吗?