mysql_real_escape_string (formerly addslashes) to prep for SQL query

Strings being passed from PHP to MySQL need to be escaped. These days one should use mysql_real_escape_string() instead of addslashes(). This new function will add slashes; It is aware of the character set of the database connection; It must be used after a database connection is established; It protects you from SQL Injection Attack. Please read up on it and use it instead of addslashes().

Sometimes PHP is set up by default to automatically add slashes to form field data. In the specific case of your script you have to consider whether PHP has added slashes automatically to your strings. Any string being used in an SQL query should have slashes added once and ONLY once.

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));
?>
Advertisements

About samehramzylabib

See About on https://samehramzylabib.wordpress.com
This entry was posted in Coding, PHP Form Processing, PHP stripslashes and addslashes and tagged , , , , . Bookmark the permalink.

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s