Reputation: 73
I've created a function called tree()
which is supposed to retrieve data from my comments
table and display comments in a thread in a hierarchy, much like the comments on reddit. The $parentid
is the id of the parent comment and the $postid
is the id of the page the comment is on. DisplayComments()
is a php function which displays the comment's data and forms, including html.
Now the issue is when I load the page the php code stops at $statement = $databaseConnection->prepare($query);
when it's done inside of the function. However, if I take the code outside of the function the code works, but I can't use the code inside of DisplayComments()
and can only show the comment replies as if they were the start of new threads.
Why can't I use this mysql query inside of a function? Is there anyway I can use it inside of a function so I can call it where I need it?
function tree($parentid, $postid) {
$query = "SELECT * FROM comments WHERE parentid = ?";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('i', $parentid);
$statement->execute();
$statement->store_result();
if ($statement->error)
{
die('Database query failed: ' . $statement->error);
}
if ($statement->num_rows >= 1)
{
$statement->bind_result($commentid, $postid, $username, $comment, $parentid, $level);
while($statement->fetch()){
if (!is_hidden($commentid, 1)){
DisplayComments($comment, $username, $postid, $commentid, $level);
}
}
}
}
Upvotes: 0
Views: 420
Reputation: 9227
Your tree function has no knowledge of $databaseConnection
. You need to pass it as another variable, e.g.
function tree($parentid, $postid, $databaseConnection) {
Have a read of the PHP manual's page on variable scope (but try not to use global
, that's rarely a good thing)
Upvotes: 1