|
|
mysql_real_escape_string() function in PHP
|
Tutorials » Php »
|
Topic |
What is mysql_real_escape_string() function in PHP?
How does mysql_real_escape_string() works?
|
|
Explanation | |
|
This mysql_real_escape_string() function in php escapes special characters in a string for use in an SQL statement.
Syntax
string mysql_real_escape_string(string unescaped_string [,resource link_identifier])
Returns the escaped string on success, or FALSE on failure.
This function will escape special characters in the unescaped_string, this differs from mysql_escape_string() by
taking into account of connection's current charset, so that it is safe to place it in a mysql_query(). This function
does not escape % and _.
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.
Example
<?php
//Attempt to connect to the default database server
$conn = mysql_connect("mysql_host", "mysql_user", "mysql_password")
or die ("Could not connect");
$item = "Zak's and Derick's Laptop";
//escape special character in the string
$escaped_item = mysql_real_escape_string($item, $conn);
//print escaped string
printf("Escaped string: %s\n", $escaped_item);
?>
|
In the above code, single quotes is escaped by back slash , now the string is an escaped string.
RESULT:
Escaped string: Zak\'s and Derick\'s Laptop
See also: mysql_escape_string() and mysql_client_encoding().
|
|
|
|