0

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.

0

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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);
}

1 Comment

function view() { $db = new mysqli("localhost", "root", "", "blog"); $sql = 'SELECT * FROM news'; return $result = $db->query($sql) or die($mysqli->error); } but this is the error i got Fatal error: Call to a member function fetch_assoc() on a non-object in C:\wamp\www\Custom-Menu\array-from-function.php on line 25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.