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.
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.