How to secure SQL query from input?
I am posting parameter to a page in php & then I have to insert it into database but I don't know how to secure the input parameter
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)
VALUES ($_POST['FirstName'], $_POST['LastName'],$_POST['Age'])");
mysqli_close($con);
?>
You can easily do this with the mysqli
set of functions by escaping those strings beforehand. The MySQL PHP drivers contains a function to safely escape strings for insertion into a string -> mysqli_real_escape_string
.
That would change your query to:
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age) VALUES ('" . mysqli_real_escape_string($_POST['FirstName']) . "', '" . mysqli_real_escape_string($_POST['LastName']) . "', '" . mysqli_real_escape_string($_POST['Age']) . "')");
This will handle the majority of your concerns with securing input for SQL.
Optionally
Take full advantage of the driver escaping for other types and safer queries by using prepared statements, which you can also do with mysqli
like:
// Prepare our query
$stmt = mysqli_prepare($con, "INSERT INTO Persons (FirstName, LastName, Age) VALUES (?, ?, ?)");
// Bind params to statement
mysqli_stmt_bind_param($stmt, "ssi", $_POST["FirstName"], $_POST["LastName"], $_POST["Age"]);
// Execute the query
mysqli_stmt_execute($stmt);
You will need to do multiple things. First of all, why are you using the usual MYSQL methods? You should use PDO objects. http://php.net/manual/en/book.pdo.php
Then you can use the prepare() method and then insert it as an array.
Please check http://php.net/manual/en/pdo.prepared-statements.php
the best thing for you to do is to use a framework like CodeIgniter, Kohana, Zend ... that already has secure classes built in. if you dont want to use the frameworks you can just take these classes.
another way, you can use ORM's. you can use redbean http://www.redbeanphp.com/ the best and easiest ORM i have ever used