Sohail Arif
Sohail Arif

Reputation: 84

PHP - Preventing SQL Injection on INSERT STATEMENT

I'll keep this short and simple, I am trying to apply some code to my insert query to prevent SQL injections. See the code below:

$insertquery = mysql_query("INSERT INTO users (firstname, lastname, email, username, password) VALUES ('".mysql_real_escape_string($fname)."', '".mysql_real_escape_string($lname)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($username)."', .'".mysql_real_escape_string($pass)."')");
            header("location:index-login-page.php?msg1=Thank you for choosing SIAA, please login.");

The above code does not insert any data but it still prints the msg1 message. What am I doing wrong or is it even possible to prevent SQL injections on an insert statement.

Thank You

Sohail.

Upvotes: 0

Views: 2334

Answers (2)

Ninju
Ninju

Reputation: 2530

Use PDO and prepared queries.Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.Have a look at below example.

($conn is a PDO object)

$conn = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $conn->prepare("INSERT INTO users VALUES(:firstname, :lastname)");
$stmt->bindValue(':firstname', $firstname);
$stmt->bindValue(':lastname', $lastname);
$stmt->execute();

Upvotes: 3

JRsz
JRsz

Reputation: 2941

Use prepared statements, this will solve the problem in any case. In this way the user input is beeing send seperatly and has no way of tampering with the Query.

http://php.net/manual/de/mysqli.quickstart.prepared-statements.php

Or How can I prevent SQL injection in PHP?

Upvotes: 1

Related Questions