problems with infinite loop using PDO::FETCH_ASSOC

Asked

Viewed 94 times

1

My Query

$sql = "SELECT * FROM tablename WHERE algumvalor=2 LIMIT 1";

It’s going into infinite loop here

How do I use while?

  while($row_data=$conn->executaQuery($sql)) 
  {
      var_dump($row_data);    
  }

With for works

$row_data = $conn->executaQuery($sql);


foreach($row_data  AS $dados){

    var_dump($dados);

}

Connection and search class

public function executaQuery($sql){
    $db = $this->conn;
    $sth = $db->prepare($sql);
    $sth->execute();
    return $sth->fetch(PDO::FETCH_ASSOC);
}
  • Your query always returns the same line.

1 answer

1


The foreach runs through all the elements array of data that returns to the end and for when you have no more data.

Already the while will always be doing the checking and the way you did it will always make the query again in the database, calling the function.

An example of how you could use while

$row_data = $conn->executaQuery($sql);
$i = 0;

while($i < count($row_data)) { 
    var_dump($row_data[$i]);
    $i++;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.