Quick Character Escaping in PHP

When writing PHP web apps, I tend to run in to a portability issue when dealing with SQL connectivity. Since I can’t count on having the PEAR DB module available, I rolled my own set of functions to interact with a MySQL database.

The problem lies in escaping characters in your SQL queries. Do I addslashes()? Is magic_quotes_gpc enabled?

My quick-and-dirty solution is the following function:

function request_cleanup()
  if(get_magic_quotes_gpc() == 0)
    foreach($_REQUEST as $req_key => $req_value)

By calling that function on every page that deals with inserting content in to the database, I know will will get my content escaped correctly.

Of course it escapes all submitted content, including that which isn’t going in to the database so don’t forget to stripslashes() when you are working with data that doesn’t need it.



$notes = $_REQUEST['notes '];
$confirmation = stripslashes($_REQUEST['notes ']);

$SQL = "INSERT INTO notes (note) VALUES ('$notes')";

print "Your note was: $confirmation";

This entry was posted in php, Programming, SQL. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *