Terungwa
Terungwa

Reputation: 427

Mysql select query/ PHP function is generating an infinite loop

I have a function that is meant to select data from a database to be displayed in a table. The function is generating an endless loop. How may I fix that?

My code is below:

function view()
{
    $db = new mysqli("localhost", "root", "", "blog");
    $sql = 'SELECT * FROM news';
    $result = $db->query($sql) or die($mysqli->error);
    return $result->fetch_assoc();
}
?>
<table>
  <tr>
    <th scope="col">Title</th>
    <th scope="col">Slug</th>
    <th scope="col">Text</th>
  </tr>
  <?php while($row = view()) { ?>
  <tr>
    <td><?php echo $row['title']; ?></td>
    <td><?php echo $row['slug']; ?></td>
    <td><?php echo $row['text']; ?></td>
  </tr>
  <?php } ?>
 </table>

Thanks.

Upvotes: 0

Views: 1087

Answers (2)

Dave
Dave

Reputation: 888

you function is re-executing the query every single time you call it.

make your function return the $result variable, and then have your while loop look like this:

<?php $result = view(); while($row = $result->fetch_assoc()) { ?>
  <tr>
    <td><?php echo $row['title']; ?></td>
    <td><?php echo $row['slug']; ?></td>
    <td><?php echo $row['text']; ?></td>
  </tr>
<?php } ?>

EDIT: your view() function should look like this:

function view()
{
    $db = new mysqli("localhost", "root", "", "blog");
    $sql = 'SELECT * FROM news';
    return $db->query($sql) or die($mysqli->error);
}

Upvotes: 2

Rodrigo Techera
Rodrigo Techera

Reputation: 251

Try this:

function view()
{
    $db = new mysqli("localhost", "root", "", "blog");
    $sql = 'SELECT * FROM news';
    $result = $db->query($sql) or die($mysqli->error);

    $results=array();
    while($row=$result->fetch_assoc())
        $results[] = $row;

    return $results;
}
?>
<table>
  <tr>
    <th scope="col">Title</th>
    <th scope="col">Slug</th>
    <th scope="col">Text</th>
  </tr>
  <?php $results = view();
        foreach($results as $result_index=>$result_values) { ?>
  <tr>
    <td><?php echo $result_values['title']; ?></td>
    <td><?php echo $result_values['slug']; ?></td>
    <td><?php echo $result_values['text']; ?></td>
  </tr>
  <?php } ?>
 </table>

Upvotes: 2

Related Questions