0

I have 2 scripts which are technically the same, but one works, and the other produces the error:

( ! ) Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 64 bytes) in C:\wamp\www\SOTag\SOTag.php on line 29

Line 29 being:

$rows[] = $r;

This is the code that works:

$this->connect_db();
$statement = $this->db_connection->prepare("SELECT * FROM tags WHERE tag LIKE :keywords");
$statement->bindParam(':keywords', $keywords, PDO::PARAM_INT);
$statement->execute(compact('keywords'));

$rows = array();
while($r = $statement->fetch(PDO::FETCH_ASSOC)) {
    $rows[] = $r;
}
return json_encode($rows);

And this is what I need to do (as I need to check for results) but it fails:

$this->connect_db();
$statement = $this->db_connection->prepare("SELECT * FROM tags WHERE tag LIKE :keywords");
$statement->bindParam(':keywords', $keywords, PDO::PARAM_INT);
$statement->execute(compact('keywords'));
$result = $statement->fetch(PDO::FETCH_ASSOC);

$rows = array();
while($r = $result) {
    $rows[] = $r;
}
return json_encode($rows);
Adam
  • 1,935
  • 2
  • 26
  • 55

3 Answers3

2

You've created an infinite loop:

$rows = array();
while($r = $result) {
    $rows[] = $r;
}

PHP is just preventing you from crashing the whole server.

Álvaro González
  • 135,557
  • 38
  • 250
  • 339
1

while($r = $result) { is the problem.

$result is always evaluated as true, so the loop never stop.

You have to do this:

while($r = $statement->fetch(PDO::FETCH_ASSOC)) {
xdazz
  • 154,648
  • 35
  • 237
  • 264
1

too much errors in your code, it's easier to rewrite it:

$statement = $this->db_connection->prepare("SELECT * FROM tags WHERE tag LIKE ?");
$statement->execute(array($keywords));
$rows = $statement->fetchAll();
return json_encode($rows);
Your Common Sense
  • 154,967
  • 38
  • 205
  • 325