简体   繁体   中英

Php push user array into users array and loop through users and user data (properties)

I have a bunch of users into a database table (named "users"), each user with properties stored in the table's columns: id, username, first_name, last_name and so on.

When a user is logged in, her/his data is retrieved from the database and displayed in a HTML table; for this purpose I have made the function (inside a functions.php file):

function user_data() {
  $users = array();
  $func_num_args = func_num_args();
  $func_get_args = func_get_args();
  if ($func_num_args > 1) {
    unset($func_get_args[0]);
    $fields = '`' . implode( '`, `', $func_get_args) . '`';
  }
  $query = "SELECT $fields FROM users";
  $result = query($query);
  $col = mysqli_fetch_assoc($result);   
  array_push($users, $col);

  print_r($users);
  return $users;
}

And then on the User's page:

$user_data = $user_data[0];
echo "<span>Welcome, " . $user_data['first_name'] . " " .    $user_data['last_name'] . "!</span>";

There are 2 users in the database yet the $users array contains only one user, as print_r($users) shows:

Array
(
[0] =&gt; Array
    (
        [username] =&gt; ajax
        [first_name] =&gt; Razvan
        [last_name] =&gt; Zamfir
        [email] =&gt; razvan.zamfir80@gmail.com
        [telefon] =&gt; 0743127315
        [oras] =&gt; Bucuresti
        [adresa] =&gt; Strada Alexandru Ipsilanti nr. 6, bloc 29E, sc. B, et. 3, ap. 83.
    )
);

I need to loop through all the users and through each user's properties to display a general table that displays a user's first name , last name and and Edit button on each row.

What am I doing wrong?

Do iterate the rows of the fields specified by your query then fetch each of them with the fetch_assoc

function user_data() {
  $users = array();
  $func_num_args = func_num_args();
  $func_get_args = func_get_args();
  if ($func_num_args > 1) {
    unset($func_get_args[0]);
    $fields = '`' . implode( '`, `', $func_get_args) . '`';
  } 

//$result = query($query);
 $conn = new mysqli("yourhost","username","pass", "dbname");
  $query = "SELECT $fields FROM users";
$result=$conn->query($query);
if ($result->num_rows > 0) {
 while ($row =$result->fetch_assoc()) {
        array_push($users,$row);
    }

    /* free result set */
    mysqli_free_result($result);

}
   print_r($users);
    return $users;
 }

Then iterate the array returned from user_data() method to extract the values.

var $usr = user_data();    
foreach ($usr as $arr){
 foreach ($arr as $key => $value){
    echo $key ." ".$value;
 }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM