1

I have the following array to add to the database.

$arr = array("a'a","b'b","c'c");

To escape the single quotes before adding to database I use this for loop

for ($i=0; $i < count($arr); $i++) { 
  $arr[$i] = addslashes($arr[$i]);  
}

And it works just fine. But if the original array is changed to this:

$arr = array("first"=>"a'a","b'b","c'c");

then I get the following error:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 150994944 bytes) in /home/filepath/file.php on line 12

I'm not sure why I get this error when the array has a custom key of "first". I wouldn't get this error if I manually use addslashes to each array value but whenever I put it in a for loop I get the error.

Does anyone have a work around for applying addslashes to each array value? I've tried mysqli_real_escape_string instead of addslashes but I got the same error.

2
  • 5
    use prepared statements for your inserts instead of adding and removing slashes Commented Jan 5, 2019 at 20:20
  • The way you are escaping is not safe , Use prepared statements and please let us see your addslashes function so we can help you. Commented Jan 5, 2019 at 20:22

1 Answer 1

1

As mentioned in the comments, you should use a prepared statement with bound variables instead of manually escaping your values (with the wrong function...).

The reason of your error, is that you have generated a never-ending loop.

At first your array has 3 elements, but as you use a numeric for loop instead of a foreach, on the first two iterations you will escape your last 2 values, indices 0 and 1. On the third iteration, you try to escape the element in your array with key 2 as $i is 2.

But there is no element in your array that has key 2. So you add a fourth element. And that happens every iteration after that; you add new elements and $i will never reach the count of your array, causing you to loop until memory runs out.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for pointing that out. You mentioned that I'm escaping my values with the wrong function. Can you tell me briefly what is the problem with using addslashes or mysqli_real_escape_string? I took a short php course online and I was told to use mysqli_real_escape_string to ensure special characters do not cause problems.
@blah Maybe take a look at stackoverflow.com/a/16315399/3783243 or the dup tagged there
@blah mysqli_real_escape_string would be better, but as you can see in the manual, there is still a big if. Better forget the escaping and simply use a prepared statement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.