Screen Shot for Thumnbails


Conn Warwicker



Portfolio

Scripts and Websites I've made using PHP and MySQL mainly.

Snippets

Code snippets and mini tutorials

Contact

Contact me if you have any questions or queries



Home / Snippets / protect_against_sql_injections

This section is new and undergoing snippet addition, as of 13/6/11

Protect Against SQL Injections



The simplest way to do this is to make sure that any user submitted/altered data you are running through an SQL query (be it SELECT, UPDATE, INSERT, etc...) is properly escaped.

What this means is that a slash "\" will be added in front of characters such as single quote ' and double quote ", as well as various others. This will stop a user injecting malicious SQL into your query, either on purpose or by accident.

E.g.

NOT SAFE:

<?php
$data = $_POST['data'];
$myQuery = mysql_query("SELECT * FROM `table` WHERE `field` = '$data'") or die('Error');
?>

SAFER:

<?php
$data = mysql_real_escape_string($_POST['data']);
$myQuery = mysql_query("SELECT * FROM `table` WHERE `field` = '$data'") or die('Error');
?>

Though you should also practice other techniques of data sanitising and validation as well.

Leave a Comment


Comment

All fields are required

Your Name


Your Email Address


Your Comment


Human Validation

What animal is this above:






Comments


No Comments Have Been Made