MySQL query with infinite loop

1

My page 'list.php' gets in infinite loop when showing values.

I used a while to show all database values

The PHP code used on the listing.php

<?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 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);
}   
    
asked by anonymous 01.04.2018 / 09:49

2 answers

1

Try to use 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; ?>
    
01.04.2018 / 17:03
1

The reason is simple, $row will never change its state to false , nor 0 nor null , consequently your loop will be 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 rows, I think. A similar behavior is done by mysqli_fetch (which explicitly says in the documentation that it 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 have already returned the result, it will be false or it will already be the object, but it will alternate between object / false at a later time.

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

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

It will be the same thing to do:

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

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

    
01.04.2018 / 11:21