Home > Net >  How to call a foreach loop from a PHP function and output results in HTML
How to call a foreach loop from a PHP function and output results in HTML

Time:03-31

Good day!

I have written a function getData() that is running a query to SELECT all data from my database.

    function getData() {

     try {

       $pdo = new PDO("mysql:host=localhost;dbname=db", 'root', '');
       $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

       $sql = "SELECT * FROM table";
       $stmt = $pdo->prepare($sql);
       $stmt->execute();

       foreach ($stmt as $row)
       {
         echo $row['username'];
       }

    } catch(PDOException $e) {

    echo "Connection failed: " . $e->getMessage();

    }

To output the data, I do a foreach loop and echo the results. No brainer, this situation works for me outside the HTML that I want to output the results in.

But, I hope to output the results inside a HTML table:

 <tbody>
  <tr>
   <?php getData();
     foreach ($stmt as $row) { ?>
       <td>
         <?php echo $row['username']; ?>
       </td>
   <?php } ?>
  </tr>
 </body>

Is there something in my code that I am missing? Am I not following a correct procedure? I hope to learn from this to better improve in the coming future and I hope I did my best to ask the question to help understand my situation.

Thank you!

CodePudding user response:

Instead of echo'ing in getData(), you should add each result to an array and return that:

function getData() {
  ....
  $results = array();
  foreach ($stmt as $row) {
     $results[] = $row; //add each result to the array
  }
    
  return $results; //return the data
}

Then in your HTML assign the result of getData(); to a variable:

$data = getData();

And then loop on the $data variable:

foreach ($data as $row) { ?>
<td>
    <?php echo $row['username']; ?>
</td>
<?php } ?>
  • Related