我有两个脚本,它们在技术上是相同的,但一个可以工作,另一个会产生错误:
( ! ) Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 64 bytes) in C:'wamp'www'SOTag'SOTag.php on line 29
第29行为:
$rows[] = $r;
这是有效的代码:
$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);
这就是我需要做的(因为我需要检查结果),但它失败了:
$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);
您已经创建了一个无限循环:
$rows = array();
while($r = $result) {
$rows[] = $r;
}
PHP只是防止你破坏整个服务器。
代码中有太多错误,重写它更容易:
$statement = $this->db_connection->prepare("SELECT * FROM tags WHERE tag LIKE ?");
$statement->execute(array($keywords));
$rows = $statement->fetchAll();
return json_encode($rows);
while($r = $result) {
就是问题所在。
$result
总是被求值为true,因此循环永远不会停止。
你必须这样做:
while($r = $statement->fetch(PDO::FETCH_ASSOC)) {