PHP: Prevent SQL Injection Attacks

Security of your website information is probably the most important thing. If your database contains valuable data, you might lose your data or your data could be stollen.
Not every web developer has heard about SQL Injection. I know, you will say "Who is going to hack my website?", "Why should anyone hack my website?" or "No one is gonna hack my website".

How SQL Injection is possible?

This is possible through user input ( POST, GET )

With SQL Injection a hacker can retrieve your data, insert, delete, so basicly can do anything with your database.

You need to sanitize input data, before being used in a sql query.PHP has two functions for mysql that sanitize user input: addslashes( older ) and mysql_real_escape_string( recommended ). This function comes from PHP >= 4.3.0, so you should check first if this function exists. Mysql_real_escape_string prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

This is a customized function I use to sanitize input data before using it into a sql query:

// this fn will add slash to the quotes

function safeEscapeString($string){
  if(get_magic_quotes_gpc()) {
    return htmlspecialchars($string);  
  } else {
    return htmlspecialchars(mysql_real_escape_string($string));


  Hayes Potter

May 1, 2008 at 4:19 PM

thnx for the info. I've heard of sql injections but never really read up on it.

-Hayes Potter
The 13 Year Old Web Developer and Programmer.

  Suresh Kumar A

May 1, 2008 at 11:54 PM

Hi Hayes Potter,
Its really very nice to hear your feedback regarding my POST. Thanxs
With regards,
A.Suresh Kumar