2

I couldn't loop through score record. It keeps replacing the score of new user but does not display the record of previous user.

Here is the code. users.php

public function show_per($matricnum)
{
    $query=$this->conn->query("select * from percentage where matricnum='$matricnum'");
    $row=$query->fetch_array(MYSQLI_ASSOC);
    if($query->num_rows>0)
    {
        $this->data[]=$row;
    }
    return $this->data;
}

viewre.php

<div class="container">
  <center><h2>Student Result Record</h2>   
  <?php 
     $i=1;
    foreach($result->data as $view)
    {?>  
  <table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Matric Number</th>
        <th>Result</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><?php echo $view['id']; ?></td>
        <td><?php echo $view['matricnum'];?></td>
        <td><?php echo $view['per'];?></td>
      </tr>
    </tbody>
    <?php $i++; }?>
  </table>
</div>
3
  • WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put $_POST, $_GET or any user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. Commented Dec 14, 2017 at 19:50
  • 1
    Thank you sir for the info. Really helpful for me. @tadman Commented Dec 14, 2017 at 20:04
  • Thank your sir @Dmitry for editing my sentences. Really appreciate it :) Commented Dec 14, 2017 at 20:06

1 Answer 1

2

Try:

public function show_per($matricnum)
{
    $query=$this->conn->query("select * from percentage where matricnum='$matricnum'");

    if($query->num_rows>0)
    {
        while ($row=$query->fetch_array(MYSQLI_ASSOC))
            $this->data[]=$row;
    }
    return $this->data;
}

You call fetch_array() method which returns only one row. You need a loop to go through all rows, then when it takes all rows it will return NULL and the while loop will stop.

And BTW, you can use fetch_assoc() instead fetch_array(MYSQLI_ASSOC).

Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer! Just wondering.. is the num_rows check necessary if you initiate the $this->data as an array? Since while($row = NULL) will stop the loop?
@GerritLuimstra You're right, it's not necessary. I kept it to remain original code as much as possible

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.