How to display comments stored from an array particularly by that email link clicked on


#1

I am trying to display only the comments posted by a particular email id. I am trying to use the GET method but I don’t understand how to proceed further with this.
I have a function that outputs all the list of the commenters and a function that displays all comments on the page. Thanks in advance.
Here is the coding for both functions:

function the_comments() {
  global $comments;

  // TODO
  echo "<h2>Comments</h2>";

     while($rows = $comments->fetch())
    {
       /*echo  "<div class = 'comments'>"
       ."<div class='comment'>".$rows['commentText']."</div>"."</div>";*/
       echo  '<div class = "comments">'
       .'<div class="comment">'. "<div class='ID'>".'Post ID: '.$rows['ID']."</div>".
       '<div class="date">'.'Posted on: .'.$rows['date'].'</div>'. '<h3>New comment by: '.$rows['email'].'</h3>'.
       '<div class="mood">'.'Current mood: '.$rows['mood'].'</div>'.
       '<div class="comment-text">'. '<p>' .$rows['commentText'].'</p>'.  '</div>'.
       '</div>'.
       '</div>';
    }
}

 function the_commenters() {
     global $filter;
     global $commenters;

          //TODO
          echo '<h2>People Who have Commented: </h2>';
           while($row = $commenters->fetch()){ 
            echo '<div class="commenters">'.'<ul>'.'<li>'.'<a href="index.php">'.$row['email'].'</a>'
            .'</li>'.'</ul>'.
            '</div>';

            
            }
            
            if($_SERVER["REQUEST_METHOD"] == "GET"){
              
            }

          }

          echo "<a href='index.php'>"."Show All Posts"."</a>";
        }

#2

What is this?

It looks like it would be a database connection, but that doesn’t mean that it stores state. Is this for WordPress?


#3

Hello @astonecipher,
No, it is not for Wordpress. It is for the database. Here are the php file codings for it:

database.php file:

<?php
require_once('config.php');
// 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;

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

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

  if($_SERVER["REQUEST_METHOD"] == "POST")
  {
    // 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)");
    $stmt->bindValue(':email',$email);
    $stmt->bindValue(':mood',$mood);
    $stmt->bindValue(':commentText',$comments);
    $stmt->bindValue(':date',$date);
    $stmt->execute();

  }
}

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

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

  $comments = $result;
}

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

  //TODO
  $query = "SELECT DISTINCT email FROM comments;";
  $rslt = $pdo->query($query);
  $commenters = $rslt;
}

Then I have index.php file:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// 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
handle_form_submission();


// Get comments from database
get_comments();
// Get commenters from database
get_commenters();

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

And then this is the file where I am having the functions in the template_functions.php:

<?php
require_once('database/database.php');
// Output comments to HTML
function the_comments() {
  global $comments;

  // TODO
  echo "<h2>Comments</h2>";

     while($rows = $comments->fetch())
    {
       /*echo  "<div class = 'comments'>"
       ."<div class='comment'>".$rows['commentText']."</div>"."</div>";*/
       echo  '<div class = "comments">'
       .'<div class="comment">'. "<div class='ID'>".'Post ID: '.$rows['ID']."</div>".
       '<div class="date">'.'Posted on: .'.$rows['date'].'</div>'. '<h3>New comment by: '.$rows['email'].'</h3>'.
       '<div class="mood">'.'Current mood: '.$rows['mood'].'</div>'.
       '<div class="comment-text">'. '<p>' .$rows['commentText'].'</p>'.  '</div>'.
       '</div>'.
       '</div>';
    }
}

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

  //TODO
  echo '<h2>People Who have Commented: </h2>';
   while($row = $commenters->fetch()){ 
    echo '<div class="commenters">'.'<ul>'.'<li>'.'<a href="index.php">'.$row['email'].'</a>'
    .'</li>'.'</ul>'.
    '</div>';
    }
    
    if($_SERVER["REQUEST_METHOD"] == "GET"){
      
    }

  }

And here is the html file along with the css file:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Database: SQL</title>

    <link rel="stylesheet" href="style.css">
  </head>
  <body>

    <h1>Database: SQL</h1>

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

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

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

        <label>
          Mood:
          <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>
          </select>
        </label>

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

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

      </form>
    </div>

    
    <?php
      the_comments();
      the_commenters();
     ?>
  </body>
</html>

css file:

    @import url('https://fonts.googleapis.com/css?family=Arvo:400,700|Monofett|Montserrat:400,700');

    html
    {
      font-family: "Montserrat";
    }

    body
    {
      background-color: rgb(180,255,255);

      max-width: 1200px;
      margin:0 auto;
    }

    h1
    {
      font-family: "Monofett";
      font-weight: normal;
      color:hotpink;
      font-size: 8vw;
      text-align: right;

      text-shadow: -1vw 1vw 0 white, -1.2vw 1.2vw 0 rgb(180,255,255), -2vw 2vw 0 white, -2.2vw 2.2vw 0 rgb(180,255,255),-3vw 3vw 0 white, -3.2vw 3.2vw 0 rgb(180,255,255),-4vw 4vw 0 white, -4.2vw 4.2vw 0 rgb(180,255,255),-5vw 5vw 0 white, -5.2vw 5.2vw 0 rgb(180,255,255), 1vw -1vw 0 rgb(80, 195, 195),2vw -2vw 0 rgb(80, 195, 195);

      padding-top:5vw;;
      padding-bottom: 9vw;
    }

    h2, h3
    {
      font-family: arvo;
    }

    .write-comment
    {
      border:10px dashed white;
      padding:1rem;
      border-radius: 10px;
    }

    .write-comment h2
    {
      font-size: 3rem;
      color:hotpink;

      padding-left:2rem;

      text-shadow:1.5rem 1.5rem 0 white, -1.5rem -1.5rem 0 rgb(80, 195, 195);
    }
    .comment
    {
      background-color: hotpink;

      border-radius: 10px;

      margin:1rem;
      box-shadow: 0px 0px 3px rgb(190, 0,100);

      color:white;


      display:flex;
      flex-wrap:wrap;

    }

    .comment>*
    {
      margin:.5rem;
    }

    .comment h3, .comment-text
    {
      width:100%;

    }

    .ID, .date
    {
      background-color: rgb(190, 0,100);
        margin:0;
        padding:.5rem;

    }

    .ID
    {
        border-radius: 10px 0 0 0;
    }

    .date
    {
        border-radius: 0 0 10px 0;
    }



    .comment-text
    {

      color:black;
      background-color: white;

      border-radius: 10px;
      box-shadow: 0px 0px 3px rgb(190, 0,100);

      padding:1rem;
    }

    form
    {
      display: flex;
      flex-wrap:wrap;
    }

    label
    {
      margin:1rem;
    }

    label:last-of-type
    {
      width:100%;
    }

    label:first-of-type
    {
      width:50%;
      display: flex;
    }

    label:first-of-type input
    {
      flex-grow:1;
    }

    button[type="submit"]
    {
      background-color: rgb(190, 0,100);
      color:white;
      font-size: 1.1rem;
      padding:.5rem;
      border:3px solid rgb(190, 0,100);
      border-radius: 5px;
      margin:.5rem;
    }

    button[type="submit"]:hover
    {

      background-color: hotpink;
    }

    textarea, input, select
    {
      border:2px solid hotpink;
      border-radius: 5px;
    }

    textarea
    {
      display: block;
      width:100%;
      height:6rem;
      resize:vertical;
    }

#4

Okay, so ideally, we want to rid ourselves of global variables. You instead want dependencies.

function the_comments() {
  global $comments;

Turns into

// we name it appropriately so we know what it actually is
function the_comments($pdo) {
//  global $comments; <-- this is now gone

now, ‘the_comments()’ doesn’t tell you what it does. Methods (or functions) should be explicit in what they do and be verbs. So, what is the intended action this function should be doing?


#5

Oh I see. But unfortunately we cannot get rid of this style the way you suggested as we have been provided with this code to work on with in the class with this format for the function. This function is to get all the comments and then outputs them; the output basically is all of the comments


#6

That’s disappointing…

So, either way, you still have to run the query from that function or pass the returned array to it for parsing.


#7

oh how we can do this?
This is the instruction we are provided:
"Set up the list of commenters so that each email address is a link; when you click on each link, the page will refresh with only comments with that email address. The page should also include a link at the bottom that reloads the page will all comments, regardless of email address, displayed.

o To set this up, you will have to conditionally modify your query for fetching posts with the contents of a GET request."


#8

So how are you triggering the request to call the database? Pass the GET variable in and use it as the parameter.


#9

I have made the connection to the database using the PDO


#10

I understand I have to do something like this:

  if($_SERVER["REQUEST_METHOD"] == "GET"){
      if(isset($_GET['email'])){

      }
    }

But I don’t understand how to proceed further on with this


#11

So, in your isset if block you need to have and execute the query, using the passed in email as the filter and then show all the comments made by that email.


#12

You mean I have to have a separate query to filter emails lets say like stored in a variable?


#13

Hello,
I tried to do this way. Is this what you mean?

  if($_SERVER["REQUEST_METHOD"] == "GET"){
    if(isset($_GET['email'])){
      $id  = $_GET['email'];
      $sql = "SELECT $id FROM comments;";
      $result = $pdo->query($sql);
       while($row = $result->fetch()){ 
         //echo $row['ID'];
         echo  '<div class = "comments">'
       .'<div class="comment">'. '<div class="ID">'.'Post ID: '.$row['ID'].'</div>'.
       '<div class="date">'.'Posted on: .'.$row['date'].'</div>'. '<h3>New comment by: '.$id.'</h3>'.
       '<div class="mood">'.'Current mood: '.$row['mood'].'</div>'.
       '<div class="comment-text">'. '<p>' .$row['commentText'].'</p>'.  '</div>'.
       '</div>'.
       '</div>';
      }
      
    }
  }

So overall I have for now so far is:

function the_commenters() {
  global $filter;
  global $commenters;

  //TODO
  echo '<h2>People Who have Commented: </h2>';
  while($row = $commenters->fetch()){ 
    echo '<div class="commenters">'.'<ul>'.'<li>'.'<a href="index.php">'.$row['email'].'</a>'
    .'</li>'.'</ul>'.
    '</div>';
  }
    
  if($_SERVER["REQUEST_METHOD"] == "GET"){
    if(isset($_GET['email'])){
      $id  = $_GET['email'];
      $sql = "SELECT $id FROM comments;";
      $result = $pdo->query($sql);
       while($row = $result->fetch()){ 
         //echo $row['ID'];
         echo  '<div class = "comments">'
       .'<div class="comment">'. '<div class="ID">'.'Post ID: '.$row['ID'].'</div>'.
       '<div class="date">'.'Posted on: .'.$row['date'].'</div>'. '<h3>New comment by: '.$id.'</h3>'.
       '<div class="mood">'.'Current mood: '.$row['mood'].'</div>'.
       '<div class="comment-text">'. '<p>' .$row['commentText'].'</p>'.  '</div>'.
       '</div>'.
       '</div>';
      }
      
    }
  }
    //$pdo = null;
    echo "<a href='index.php'>"."Show All Posts"."</a>";

  }

#14

So, that select statement isn’t correct for a few reasons. 1, the syntax is wrong. 2, you are missing the where clause to limit them to just that commenter.


#15

Oh how about this one? I am not sure how to include the variable with SQL :frowning:

$sql = "SELECT email FROM comments WHERE email = " .$id;


#16

@astonecipher is this what u mean?


#17

try this instead:

$sql = "SELECT email FROM comments WHERE email = :postEmail";
$pdo->execute(array(':postEmail' => $your_variable));

#18

Hello @johnphpnewb,
Thanks for ur response.
But I don’t understand why are we using :postEmail in the WHERE clause? I have to make use of the GET method to get the emails and have to display the comments related with that email link clicked on


#19
:postEmail

will allow you to use a variable in the execution of your query.

edit:

:postEmail is a placeholder for your variable.
I didn’t take the time to read your code in order to know if the method is get or post.
Anyway, it is not a command, rather a placeholder. Thus, you could change it:

:johnphpnewbIsAnIdiot

#20

Oh I see. Ok. So u mean I use that instead of including the variable in the sql query.
I am still confused about the $your_variable part and how will I use the GET method as I am supposed to use the GET method.

what will the $your_variable be in this case I am stuck what will I be including in that place and how will this help in echoing out the email on the page by clicking the email address link? I am supposed to echo this statement here if the user clicks on the email link and this statement will echo the id, email, comment,date,and mood of that email user:

   echo  '<div class = "comments">'
        .'<div class="comment">'. '<div class="ID">'.'Post ID: '.$row['ID'].'</div>'.
        '<div class="date">'.'Posted on: .'.$row['date'].'</div>'. '<h3>New comment by: '.$id.'</h3>'.
        '<div class="mood">'.'Current mood: '.$row['mood'].'</div>'.
        '<div class="comment-text">'. '<p>' .$row['commentText'].'</p>'.  '</div>'.
        '</div>'.
        '</div>';