1

I am using the below code to get the users list from my db:

if ($result = mysqli_query($mysqli, "SELECT user_name, name, surname, avatar, user_email FROM users")) {


    while ($row = $result->fetch_assoc()) {
        $username[]  = $row["user_name"];
        $user_email[] = $row["user_email"];
        $user_name[] = $row["name"];
        $user_surname[] = $row["surname"];
        $avatar[] = $row["avatar"];

    }

    $result->close();
}

But I get the below error:

Fatal error: [] operator not supported for strings

2
  • 1
    did you initialise all those variables ($username, $user_email, ... etc) as arrays before using them? Commented Apr 27, 2015 at 13:12
  • mySQL get data intro an asociative array....??? what is the question Commented Apr 27, 2015 at 13:15

4 Answers 4

1

This is probably what you want to do:

   $rows = array();
   while ($row = $result->fetch_assoc()) {
       $rows[] = $row;
   }
   // $rows is now an array that contains each individual row from your result set

You can then do whatever you want with that data, eg display it in a table or whatever.

  foreach($rows as $user)
  {
    echo $user['user_name'] . ' - ' . $user['user_email'];
  }

And so on

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

Comments

1

Your $username variable has been set as a string somewhere in the code before the codeblock you have posted. If you use $username=array(); you will loose that variable. I don't know if you need it or not.

Here is a better way to do :

$users = array();
while ($row = $result->fetch_assoc()) {

$users[]  = array(
        "username" => $row["user_name"],
        "email"    => $row["user_email"],
        "name"     => $row["name"],
        "surname"  => $row["surname"],
        "avatar"   => $row["avatar"]
    );

}

And you can loop the users using foreach:

foreach($users as $user){
   echo $user["username"];
   echo $user["email"];
}

Comments

0

you should take an empty array befor loop if you want these into array. like this

 if ($result = mysqli_query($mysqli, "SELECT user_name, name, surname, avatar, user_email FROM users")) {

    $results=array();

        while ($row = $result->fetch_assoc()) {
            $results []=$row;

        }

        $result->close();
    }

other wise you should remove []

Comments

0

You can do this also -

$user_data = array();
while ($row = $result->fetch_assoc()) {
    $user_data[]  = $row;
}

By this you can get all the data in a single array. The keys will be the same as database fields.

Comments

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.