Unable to display comments stored in an array as output on html page


I am trying to store the comments that are stored in the database into an empty array named $comments in a function named get_comments(). Later on I want to display the comments in another php file in a function called the_comments(). I tried to call the function and echo $comments but unfortunately there is no output displayed stored in the array. The comments are getting stored in the while loop and on echoing there inside while loop all the comments are getting displayed.
Thanks in advance.

Here are my php files:
database.php file:
// Should return a PDO
function db_connect() {

  try {
    // TODO
    // try to open database connection using constants set in config.php
    // return $pdo;
    $servername = DBHOST;
    $databasename = DBNAME;
    $user = DBUSER;
    $password = DBPASS;

    $pdo = new PDO("mysql:host=$servername;dbname=$databasename",$user,$password);
    $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $pdo;
  catch (PDOException $e)

// Handle form submission
function handle_form_submission() {
  global $pdo;

    // TODO
    // Prepare the submitted form data and insert it to the database
    $email = $_POST['email'];
    $mood = $_POST['mood'];
    $comments = $_POST['comment']; 
    $date = date('Y-m-d');

    $stmt = $pdo->prepare("INSERT INTO comments (email,mood,commentText,date) VALUES(:email,:mood,:commentText,:date)");


// Get all comments from database and store in $comments
function get_comments() {
  global $pdo;
  global $comments;

  $sql = "SELECT * FROM comments ORDER BY ID DESC";
  $result = $pdo->query($sql);
   while($row = $result->fetch()){
     $comments = $row['commentText'];
     //echo $comments."<br>";

   //$pdo = null;

// Get unique email addresses and store in $commenters
function get_commenters() {
  global $pdo;
  global $commenters;



another php file:

    // Output comments to HTML
    function the_comments() {
      global $comments;

      // TODO
      echo "<div class = 'comments'>"."<div class='comment>".$comments."</div>"."</div>";


    // Output unique email addresses to HTML
    function the_commenters() {
      global $filter;
      global $commenters;




What output are you getting? You may very well have a fatal php parse error somewhere in your actual code, because you haven’t shown the full code needed to reproduce the problem (there’s no main code that calls the functions.)

Next, this is not how to write functions. Functions should accept all input data as call time parameters (this includes the database connection credentials and form data), perform the processing they were designed to do, and return the result to the calling code (functions should not echo/output anything, it’s the responsibility of the calling code to know what to do with the result from a function.) You should not be using the global keyword everywhere to make your functions work. This results in spaghetti code/data that’s hard to troubleshoot.

Lastly, don’t unconditionally output database errors onto a web page (your die($e->getMessage()) statement.) For a connection error, there’s no reason for your code to catch and output it. Remove the try/catch logic and let php handle the connection error, where it will use its error_reporting, display_errors, and log_errors settings to control what happens with the actual error information. When learning, developing, and debugging code/queries, you would display all errors. When on a live/public server, you would log all errors.


Thanks for response and sorry for incomplete file sharing. Actually I am not getting any output and we have been asked to work on the files provided as a starter code. Unfortunately we cannot get rid of this design (which is not a good design).
The other files related with this are

The index.php file which has the $comments array defined there:

        ini_set('display_errors', 1);

        // global array of posts, to be fetched from database
        $comments = [];
        // global array of unique commenter email addresses to be fetched from db
        $commenters = [];

        require_once 'database/database.php';
        require_once 'templates/functions/template_functions.php';

        //connect to database: PHP Data object representing Database connection
        $pdo = db_connect();
        // submit comment to database

        // Get comments from database
        // Get commenters from database

        // include the template to display the page
        include 'templates/index.php';

The file that has html part is also called index.php and has this code:

<!DOCTYPE html>
    <meta charset="utf-8">

    <link rel="stylesheet" href="style.css">

    <h1>Databases: SQL</h1>

    <div class="write-comment">
      <h2>Post a Comment</h2>

      <form action="index.php" method="post">

          Email Address:
          <input type="email" name="email">

          <select name="mood">
            <option value="happy">Happy</option>
            <option value="sad">Sad</option>
            <option value="excited">Excited</option>
            <option value="bored">Bored</option>
            <option value="angry">Angry</option>

          Enter a Comment:
          <textarea name="comment"></textarea>

        <button type="submit" name="button">Post Comment</button>



I hope this will help.
Thank You


This is the template_functions.php file where we have to complete the function to get the comments and display them on the page.


Actually, you are getting output, the form is being displayed, but the comment section is not being displayed.

If you do a ‘view source’ of the output in your browser, you will see what is happening and can probably find and fix the problem.

As to fixing this specific problem, you need to use the SIMPLEST syntax/code that accomplishes a task. This will reduce the clutter and make it easier to write error free code or see mistakes in the code. There’s no good reason to concatenate all those strings making up the output in question. The following is equivalent to what’s in the code now and should make it easier to spot the mistake that’s causing the output to not be displayed -

echo "<div class='comments'><div class='comment>$comments</div></div>";


@phdr Yup I get it now :slight_smile: There was a small syntax error. Thank You
Ya one more question. I don’t know why I am not able to get the whole comments stored in the array. I understand it is because of the local scope of the while loop that is displaying the last content in the array but I don’t understand how to pull out every comment that I had stored using the while loop in the $comments


In your previous thread, though it wasn’t clearly posted, you should fetch the set of data using the ->fetchAll() method. This would replace the entire while loop.

Use the ->fetch() method to fetch data from a query that will return at most one row. Use the ->fetchAll() method to fetch data from a query that will return a set of data.

The ->fetchAll() method will return an array of row(s), which is what your $comments array is supposed to contain. You would need to loop over this array at the point where you are producing the output (a foreach(){} loop would be advisable.)

Another issue, you should list out the columns you want in the SELECT term in the query. This helps to document what you are doing and will only retrieve the columns that you want.


You mean I get rid of the while loop and use fetchAll() method and then for the select query I filter the commentText column? And then in another php file where I have to output comments using the function I use a foreach loop there?


I tried this way:
I am not sure if u meant this way

function get_comments() {
  global $pdo;
  global $comments;

  $sql = "SELECT comments FROM comments ORDER BY ID DESC";
  $result = $pdo->query($sql);

   while($rows = $result->fetchAll()){
     $comments = $rows;
     echo "<pre>";
     //echo $comments."<br>";