Marnix Verhulst
Marnix Verhulst

Reputation: 171

Warning: Illegal string offset in PHP

I want to print out the data of users with an inner join but it won't work. The array is filled up correctly in the function and before the foreach but it keeps telling me:

Warning: Illegal string offset in PHP

THE ARRAY BEFORE THE FOREACH

array (size=6)
  'user_id' => string '1' (length=1)
  'name' => string 'Vandenbergh' (length=11)
  'surname' => string 'Jan' (length=3)
  'avatar' => string '1394041001.jpg' (length=21)
  'member_id' => string '21' (length=2)
  'group_id' => string '18' (length=2)

FUNCTION

public function getMembersInfo($group_id)
{
    var_dump($group_id);
    $db = new Db();
    $select = "SELECT u.user_id, u.name, u.surname, u.avatar, g.member_id, g.user_id, g.group_id FROM tblusers u INNER JOIN tblgroup_member g ON u.user_id = g.user_id WHERE g.group_id=" . $group_id .  "";

//  $result = $db->conn->query($select);
    //return $data=$result->fetch_assoc();

    $result = $db->conn->query($select);

$result_data = mysqli_fetch_assoc($result);
    var_dump($result_data);
return $result_data;

}

PHP

$memberinfo = $group->getMembersInfo($group_id);
var_dump($memberinfo);


 <?php 
        var_dump($memberinfo)   ;
      foreach ($memberinfo as $info) {
            echo "<p>" . $info['name'] . $info['surname'] . "</p>";

      }

        ?>

Upvotes: 0

Views: 2269

Answers (1)

jonnu
jonnu

Reputation: 728

You are only getting one array from your getMembersInfo method, not an array of arrays. So, when you write foreach ($memberinfo as $info), you're iterating over just one row from your database.

Comment out the lines for yourself, and see:

var_dump($memberinfo);
//foreach ($memberinfo as $info) {
    $info = $memberinfo;
    echo "<p>" . $info['name'] . $info['surname'] . "</p>";
//}

To fix this, either remove the foreach loop, or append the results from your MySQL query inside the getMembersInfo() method into an array.

Upvotes: 4

Related Questions