1

I can't seem to get the array to return from the function correctly, every time I run the script it just echoes out 0, even though I have checked that the MySQL query returned at least 1 row. I've also tried using $_GLOBALS["FORUM_ANSWERS"][] = ..., however it still did not work.

public function getAnswers() {
    $dbh = $this->dbh;
    $id = $this->question_id;
    $q = $dbh->prepare("SELECT * FROM answers WHERE question_id = :id");
    $q->bindParam(":id", $id);
    $q->execute();
    $nr = $q->rowCount();
    if ($nr == 0) {
        echo "No Questions";
    }

    $_GLOBALS["FORUM_ANSWERS"] = [];
    while ($row = $q->fetch(PDO::FETCH_ASSOC)) {

        array_push($_GLOBALS["FORUM_ANSWERS"], array(
            "num_id" => $row["num_id"],
            "question_id" => $row["question_id"],
            "answer" => $row["answer"],
            "name" => $row["name"],
            "username" => $row["username"],
            "ip" => $row["ip"],
            "date" => $row["date"],
        ));
    }

    return $GLOBALS["FORUM_ANSWERS"];
}

SEPERATE FILE:

$answers = $forum->getAnswers();
echo count($answers);
3
  • On a side note, do you need to set this as a $GLOBALS? Commented Dec 23, 2015 at 5:52
  • if you while ($row = $q->fetch(PDO::FETCH_ASSOC)) { print_r($row); does that produce the arrays? Commented Dec 23, 2015 at 5:53
  • 1
    @objective_d noticed the problem. That being said, if you are trying to set to global try not to. Setting to global is not best practice, so-to-speak. Commented Dec 23, 2015 at 5:53

1 Answer 1

4

You are assigning to $_GLOBALS and returning $GLOBAL.

You actually don't need to use a global array by the look of it - I would just assign the array to a variable (that you initialise in the function) and return that.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm returning $GLOBALS["FORUM_ANSWERS"];, am I not?
Notice the underscore $_GLOBALS vs $GLOBALS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.