Friday, March 27, 2009

mysql_real_escape_string funciton in PHP

mysql_real_escape_string function Escapes special characters in a string for use in a SQL statement

Syntax:
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )

Escapes special characters in the unescaped_string , taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used. This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

Returns the escaped string, or FALSE on error.

Example

<?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));
?>

Note:Using mysql_real_escape_string() around each variable prevents SQL Injection.
Note 2 mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.

0 comments:

Post a Comment