Forum Moderators: coopster

Message Too Old, No Replies

How to use Mysql real escape string on an Array

How do i use mysql_real_escape_string on an array?

         

Robeysan

8:34 am on Jun 18, 2009 (gmt 0)

10+ Year Member



My array is called $shonet. It is an associative array with 6 key/values.

Here is what I am trying:


foreach($shonet as $value){
$value = mysql_real_escape_string($value);
}

But I get this err when the script runs:
Warning: mysql_real_escape_string() expects parameter 1 to be string, array given in /html etc.
Warning: Invalid argument supplied for foreach() in /html etc

What im I doing wrong here or should I be trying something different?

coopster

11:32 am on Jun 18, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



The foreach [php.net] control structure works on a copy of the array.

Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself.

You can either reference the array (in PHP5) as shown in the examples on the manual page or you can assign the updated values to a different array.

If you intend to update every value in the array, one of my favorites is to use array_map [php.net].

Pico_Train

2:42 pm on Jun 19, 2009 (gmt 0)

10+ Year Member



I do it with foreach and it works fine. Maybe I am missing something.

In your example above $value must still be an array so you would need another foreach($value as $v) in there.

$array = array();

foreach($array as $key=>$a)
{
$array[$key] = mysql_real_escape_string($a);
}

print_r($array);

When you print_r $array you'll see your data that needed escaping will be escaped.

Pico_Train

2:44 pm on Jun 19, 2009 (gmt 0)

10+ Year Member



Looking at it again, your whole expression is strange

$shonet becomes $value then $value is equal to escaped $value. I think you might be confusing the crap out of your machine...

bkeep

8:18 pm on Jun 21, 2009 (gmt 0)

10+ Year Member



I use this as a function and so far it seems to do the trick

//Check if magic qoutes is on then stripslashes if needed
function codeClean($var)
{
if (is_array($var)) {
foreach($var as $key => $val) {
$output[$key] = codeClean($val);
}
} else {
$var = strip_tags(trim($var));
if (function_exists("get_magic_quotes_gpc")) {
$output = sqlEscapeString((get_magic_quotes_gpc())? stripslashes($var): $var);
} else {
$output = sqlEscapeString($var);
}
}
if (!empty($output))
return $output;
}

just pass the array through the function as is the function does all the work

$array = codeClean($some_array);

Pico_Train

8:48 am on Jun 22, 2009 (gmt 0)

10+ Year Member



Yes good point by bkeep to check if it is a one-dimensional array. In my case you could skip the foreach and

mysql_real_escape_string($var);