PHP: mysql_escape_string - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

mysql_fetch_array mysql_error

Last updated: Sat, 27 Jan 2007

view this page in

# mysql_escape_string

(PHP 4 >= 4.0.3, PHP 5)

mysql_escape_string -- Экранирует SQL спец-символы для mysql_query.

## Описание

string mysql_escape_string ( string unescaped_string )

Функция экранирует все спец-символы в `unescaped_string`, вследствие чего, её можно безопасно использовать в mysql_query().

> Замечание: mysql_escape_string() не экраинрует `%` и `_`.

> Функция идентична mysql_real_escape_string(), исключая то, что mysql_real_escape_string() принимает параметром ещё и указатель на соединение и экранирует в зависимости от кодировки. mysql_escape_string() не делает этого и результат работы не зависит от кодировки, в который вы работаете с БД.

Пример 1. Пример использования mysql_escape_string()

`<?php $item = "Zak's Laptop"; $escaped_item = mysql_escape_string($item); printf ("Escaped string: %s\n", $escaped_item); ?>`

Вышеописанный пример выдаст следующий результат:

    Escaped string: Zak\'s Laptop

См. также mysql_real_escape_string(), addslashes() и директиву magic_quotes_gpc.

add a note User Contributed Notes
mysql_escape_string
eth at ethaniel dot com
19-Aug-2006 12:26
`a way to clean _POST _GET and _COOKIE along with their registered global variables.
<?php
function cleanmysql($arr,$arr2) {
foreach ($arr as $gt1=>$gt2) {
if (is_array($arr[$gt1])) {
list($arr[$gt1],$arr2[$gt1])=cleanmysql($arr[$gt1],$arr2[$gt1]);
} else {
$gt2=mysql_escape_string($gt2);
$arr[$gt1]=$arr2[$gt1]=$gt2;
}
}
return array($arr,$arr2);
}
list($_GET,$GLOBALS) = cleanmysql($_GET,$GLOBALS);
list($_POST,$GLOBALS) = cleanmysql($_POST,$GLOBALS);
list($_COOKIE,$GLOBALS) = cleanmysql($_COOKIE,$GLOBALS);
?>`
info at globalissa dot com
17-Aug-2006 03:37
`We need to distribute code compatible with as many servers as possible. We use this little function on user submitted data:
// http://php.net/mysql_escape_string used for wider isp host support - start
if(!function_exists('escape_smart')){
// Quote variable to make safe
function escape_smart($value)
{
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote if not integer
if (!is_numeric($value)) {
$value = mysql_escape_string($value);
}
return $value;
}
}`
mbr at arlsoft dot com
31-Jul-2005 07:52
`steve at tequilasolutions dot com suggests base64_encode() as a
better choice than bin2hex(). Unfortunately, it's not that
simple. Since serialize() can be used with either of them, I
won't consider it in this argument. But it's important to
consider not only what happens when you store the data with an
INSERT or UPDATE, but also what happens when you later fetch the
data with a SELECT.
Storing data using INSERT or UPDATE:
Size of the string in the PHP variable:
base64_encode(): approx. 1.33 * length of the data
bin2hex(): 2 * length of the data
Size of data transmitted to the MySQL server:
base64_encode(): approx. 1.33 * length of the data
bin2hex(): 2 * length of the data
Size of data stored in the MySQL server:
base64_encode():
The SQL parser will see the argument "..." and store
whatever bytes it finds inside the quotes. So the
disk space required to store this is approx. 1.33
times the length of the data.
bin2hex():
The SQL parser will see the argument x'...',
recognize it as indicating that the argument is
encoded as hexadecimal, convert it back a string half
the length of the hex representation, and store the
result. So the disk space required to store this is
the same as the original length of the data.
Fetching data using SELECT:
Size of data transmitted from the MySQL server:
base64_encode():
The same as what's stored in the database -
approx. 1.33 times the length of the original data.
bin2hex():
The same as what's stored in the database - the
length of the original data
I've summarized the comparison below:
Storing data:
processing time on the PHP side
unknown whether base64_encode() or bin2hex() runs faster.
bandwidth
base64_encode() transmits fewer bytes across the link.
processing time on MySQL side
unknown whether decoding hex inside x'' (the bin2hex()
case) is notably slower than searching inside "" for (and
not finding any) characters escaped by a backslash (the
base64_encode() case).
data storage in MySQL
bin2hex() is better - base64_encode() inflates data by
about 33%, whereas the data encoded by bin2hex() is
placed inside quotes that cause it to be deflated back to
its original size before it is stored.
Fetching data:
bandwidth
bin2hex() is better - data encoded by base64_encode()
before storage will have been inflated by about 33%.
processing time on the PHP side
bin2hex() is better - since the data was already decoded
by the SQL parser before it was stored, bin2hex()
requires no decoding, whereas data encoded by
base64_encode() before storage must be decoded by
base64_decode() whenever it is fetched.
Summary:
The bin2hex() approach seems better for something like a
store catalog, which changes infrequently, but which is
viewed frequently (the store owners hope :-) ).
The base64_encode() approach seems better for something like
a network management system which constantly logs alarms from
network devices, but which is queried infrequently.`
steve at tequilasolutions dot com
24-May-2005 01:57
`Also... (see previous) I don't bother because my blobs are always multimedia files so don't compress well but if you were storing word docs etc adding compression into the mix saves space and will often be smaller than the original data.
e.g, - off the top of my head this, not syntax checked
$x = enc($mydata);
mysql_query("insert into table values('$x')");
function enc($x){
return base64_encode(bzcompress(serialize($x),9));
}
function dec($x){
return unserialize(bzdecompress(base64_decode($x)));
}`
steve at tequilasolutions dot com
23-May-2005 07:39
`Rather than bin2hex use a combination of serialise and base64. Data gets 33% bigger than source but with bin2hex data gets 90% bigger.
I have two functions for encoding and decoding data before use in sql. Using serialse preserves the datatypes so that you can insert any data you like, arrays etc.
function enc($x){
return base64_encode(serialize($x));
}
function dec($x){
return unserialize(base64_decode($x));
}`
codeslinger at compsalot dot com
05-Feb-2005 12:49
`er um... version_compare did not exist prior to 4.1.0
in any case, adding slashes and dealing with magic quotes etc. is a sure recipe for major headaches.
You can avoid a whole slew of problems by converting your strings to hex (bin2hex) before passing them to mySQL
mySQL will accept any value in the form of
0xFEAC1234...
It will then automagically convert it back to a string for storage and retrieval while avoiding all of the zillions of problems with special characters.
I have done this with some very large records and never had a problem.`
04-Feb-2005 12:03
`Here's the solution I came up with for unescaping. I'm not a "real" programmer so there's probably some huge problem with this. I've been using it for a while and it seems to work okay though.
function escape_string($string) {
$string = nl2br($string);
if(version_compare(phpversion(),"4.3.0")=="-1") {
$string = mysql_escape_string($string);
} else {
$string = mysql_real_escape_string($string);
}
return $string;
}
function unescape_string($string) {
stripslashes($string);
$string = str_replace('<br />', Chr(13), $string);
return $string;
}`
boris-pieper AT t-online DOT de
15-Jan-2005 03:07
`Using a function like escape_string make sure you allways use optimal escape function...
Note: You should use mysql_real_escape_string() (http://php.net/mysql_real_escape_string) if possible (PHP => 4.3.0) instead of mysql_escape_string().
<?php
function escape_string ($string) {
if(version_compare(phpversion(),"4.3.0")=="-1") {
mysql_escape_string($string);
} else {
mysql_real_escape_string($string);
}
}
?>`
add a note
mysql_fetch_array mysql_error

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 10:36:09 2007 PST