Daniel
Daniel

Reputation: 31

When should you escape strings used in MySQL

I'm fairly new to PHP but have been familiar with StackOverflow for a while.

I have recently been reading about appropriate times to use mysql_real_escape_string and would appreciate any advice on the following.

Is using mysql_real_escape_string once, on the initial $_POST variable enough to secure the string through the script?

For example:

$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
$email = mysql_real_escape_string($_POST["email"]);
$repeat_password = mysql_real_escape_string($_POST["repeat_password"]);

I declare these values before running a bunch of if statements and finally once the if statements are finished I make an INSERT into the mysql database:

mysql_query("INSERT INTO users (username, password, email, signup_date) VALUES ('$username', '$password', '$email', CURDATE())") or die(mysql_error());

mysql_real_escape_string is not used anywhere else throughout the if statements - is this safe enough for a rookie to use whilst still maintaining some injection protection?

Upvotes: 2

Views: 148

Answers (3)

Lawrence Cherone
Lawrence Cherone

Reputation: 46650

While mysql_real_escape_string() may (currently) protect you from SQL injection its deprecated so you should not you the mysql_* functions anyway, in future versions of PHP It will be removed rending your code useless.

Why drive a bashed up old ford fiesta when you have the keys to a shiny new Lamborghini?

Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Upvotes: 1

rmcfrazier
rmcfrazier

Reputation: 444

Try a prepared statement:

$stmt = $con->prepare("INSERT INTO users (`username`, `password`, `email`, `signup_date`) VALUES (?, ?, ?, ?)");
$stmt->bind_param($username,$password,$email,CURDATE());
$stmt->execute();
$stmt->close();

Upvotes: 0

CanSpice
CanSpice

Reputation: 35828

No, this is not safe. You should switch to prepared statements.

Upvotes: 1

Related Questions