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:
<?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;
$pdo = new PDO("mysql:host=$servername;dbname=$databasename",$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->bindParam(':email',$email);
$stmt->bindParam(':mood',$mood);
$stmt->bindParam(':commentText',$comments);
$stmt->bindParam(':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);
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;
//TODO
}
another php file:
<?php
require_once('database/database.php');
// Output comments to HTML
function the_comments() {
global $comments;
// TODO
get_comments();
echo "<div class = 'comments'>"."<div class='comment>".$comments."</div>"."</div>";
}
// Output unique email addresses to HTML
function the_commenters() {
global $filter;
global $commenters;
//TODO
}