Mysql query with infinite loop

Asked

Viewed 334 times

1

My 'listing.php' page loops infinitely when displaying values.

I used a while to display all database values

The PHP code used in the page php listing.

<?php while($row = $resultado):?>
  <tr>
    <td><?php echo $row->ID; ?></td>
    <td><?php echo $row->courseName; ?> </td>
    <td><?php echo $row->name; ?> </td>
    <td><?php echo $row->date; ?> </td>
    <td><?php echo $row->comment; ?></td>
    </tr>
<?php endwhile;?>

The function with the Query is written like this:

function selectAll(){
    $this->connect();
    $resultSet = $this->pdo->query("SELECT comment.ID, courseName, name, date, comment FROM comment, course, teacher WHERE teacher.idCourse = course.ID AND comment.idTeacher = teacher.ID;");
    return $resultSet->fetch(PDO::FETCH_OBJ);
}   
  • Ever tried to make a foreach ? foreach ($result as $Row)

  • Not yet, I’ll try here and see if I can.

2 answers

1


Try to use the foreach:

<?php foreach($resultado as $row): ?>
  <tr>
    <td><?= $row->ID; ?></td>
    <td><?= $row->courseName; ?></td>
    <td><?= $row->name; ?></td>
    <td><?= $row->date; ?></td>
    <td><?= $row->comment; ?></td>
  </tr>
<?php endforeach; ?>
  • Gave the following error: "Warning: Invalid argument supplied for foreach() "

  • how did you set up the structure of foreach ? would you like to copy your foreach code and paste here

  • The problem seems to be in the return of the selectAll function, where it does not seem to send an argument accepted by foreach.

  • The argument that the foreach wait is an array

  • 1

    Solved, I changed the return of selectAll to return $resultSet->fetchAll(PDO::FETCH_ASSOC);.

1

The reason is simple, the $row will never change its state to false, nor 0 and neither null, consequently your loop will become infinite.

You’ve probably seen something like this:

while( row = pdo->query("SELECT * FROM tabela") ){
}

The query will return false when there are no more lines, I think. A similar behavior is done by mysqli_fetch (which explicitly says in the documentation that will return NULL when "No more Rows/data exists or data truncation occurred").


But... This is not your case. Since, when you do:

return $resultSet->fetch(PDO::FETCH_OBJ);

You already returning the result, it will be false or it will already be the object, but it will switch between object/false at a later time.

If the result of query have a result, have at least one line, then you will return an object and therefore whenever you do:

<?php while($row = $resultado):?>

Will be the same as doing:

<?php while($row = (object)[""]):?>

Both the $resultado as to the (object)[""] will never be false, in this case, then your loop will be infinite.

  • Although I didn’t present the solution, it was VERY useful so I could understand the reason for the loop and add some knowledge. Thank you!!!

Browser other questions tagged

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