-2

I have a function as below, but when I echo $user_data['first_name']; it pop out

Undefined index: first_name.

can anyone help out?

$user_data = user_data($con, $user_id, $fields);

echo $user_data['first_name'];
// pop out error Undefined index: first_name.



function user_data($con, $user_id, $fields) {

    $data = array();
    $fields = implode(', ', $fields);
    $result = mysqli_query($con, "SELECT $fields FROM users WHERE user_id= $user_id");
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    } 

    return $data;

} 

$con = new mysqli('localhost', 'username', 'password', 'database_name');

$fields = array('first_name', 'last_name','color');

$user_id = 1;

$data = user_data($con, $user_id, $fields); 
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Ron Pang
  • 9
  • 3

3 Answers3

0

Because you will get data in array. So you need to traverse from other. Change your code like:

$user_data = user_data($con, $user_id, $fields);
foreach($user_data as $user){
  echo $user['first_name'];  
}
B. Desai
  • 16,414
  • 5
  • 26
  • 47
0

Try this:

echo $user_data[0]['first_name'];
TheCleverIdiot
  • 412
  • 4
  • 19
0

The connection is created at the last line in the script given and after that only the database can be accessed so echo the result after using array traversal loops like Foreach,etc. Add this line at the end of your script:

foreach($user_data as $user){
  echo $user['first_name'];  
}