Using PHP/MySQLi I wanted to extract some data to an array. The data is a few megabytes in size:
The code to get the table dump of this data follows:
error_reporting(E_ALL);
$q = "SELECT * FROM mytable";
if (!$result = $mysqli->query($q)) {
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $query . "\n";
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
return $ret;
}
if ($result->num_rows === 0) {
$ret = 0;
return $ret;
}
$ret = array();
while($row = $result->fetch_array()){
array_push($ret, $row);
}
echo mb_strlen(serialize((array)$ret), '8bit');
When executing the following code I got:
But it said tried to allocate 28672 bytes which is nowhere near the limit. Why is this?
Think of it this way.
You've got $100. You go to the candy store, and decide to buy 200 $1 candy bars, one-by-one (your
while
loop).The first 100 purchases are going to go through, but the next time you try buying a $1 candy bar, you're going to get told "you tried to spend a dollar, but you've already spent $100".
PHP is reporting the amount of memory your last instruction attempted to use. In this case, it's probably the
array_push($ret, $row);
call.