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

NO.

That is HIGHLY vulnerable to sql injection attacks.

Instead of using mysql_real_escape_string, I suggest using prepared statements.


Use mysql_real_escape_string.


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

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

Tags:

Mysql

Php