0

I have created an array in my functions.php file to be accessed on another page. I then returned the array and called it on a different page. This is what I have:

In my functions.php file I have

public function getpostcontent($userid){
    include('db-conx.php');
    $getval = "SELECT `content`,`date` FROM posts WHERE userid = ?";
    $stmt = $conn->stmt_init();
    if ($stmt->prepare($getval))
    {
        //$userid = $_SESSION['userid'];
        $stmt->bind_param("s", $userid);
        $stmt->execute();
        $stmt->bind_result($content, $date);
        while ($stmt->fetch()) {
            $displayname = getdisplayname($userid);
            $array = [
            "content" => $content,
            "date" => $date,
            ];
        }
        return $array;

    }
}

And I access the array on my other page using this.

$posts = new getposts();
$returned=$posts->getpostcontent($userid);
foreach($returned as $val)
{
    echo $val['content'];
}

I've tried all the solutions I found on google and elsewhere with no luck. It works when I use print_r($val); to retrieve all elements in the array but throws the 'Illegal string offset' when I try to access them individually. Help?

2
  • Can you paste your print_r($val) array? Let's see what it looks like. Commented Dec 13, 2014 at 3:39
  • You're reassinging $array to a one-dimensional array in getpostcontent loop, so returned in your main code will be only one dimension ($returned['content'] and $returned['date']). Commented Dec 13, 2014 at 4:08

1 Answer 1

1

One problem I can see is that in each iteration of

while ($stmt->fetch())

it's writing over the variable $array every time and eventually it returns the last array. Change

$array 

to

$array[] 

in order to collect each iteration and so the for loop isn't just iterating the key value pairs of one array.

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

1 Comment

Thank you sooo much. I can finally sleep well tonight because of you. You're a life saver. I would upvote this a million times if I could. Thanks again :)

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.