简体   繁体   中英

Trying to use mysql query inside of a php function to call data from database.

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);
            }   
        }
    }
}

Your tree function has no knowledge of $databaseConnection . You need to pass it as another variable, eg

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM