user3131209
user3131209

Reputation: 31

Fail to get all usernames from table

I'm trying to retrieve all usernames listed in my members table, list them in a page and link them to their user profile. This is how I retrieve the usernames of the members table:

$result = mysqli_query($mysqli,"SELECT username FROM members");
$row = mysqli_fetch_array($result);
$username = $row['username']; 

In order to link them, I'll be using the following:

<?php 
foreach ($result as $row) {
?>
    <a href="#"><?php echo $username ?></a>
<?php
}
?>

The problem is that it's only showing 1 username, 5 times. So I get like:

username1 username1 username1 username1 username1

rather than

username1 username2 username3 username4 username5

What am I doing wrong? (sorry, recently started learning PHP/MYSQL so I'm quite new to it.

Upvotes: 0

Views: 90

Answers (3)

Sparky
Sparky

Reputation: 15085

Try this:

$result = mysqli_query($mysqli,"SELECT username FROM members");
$row = mysqli_fetch_array($result);

<?php 
foreach ($result as $row) {
    $username = $row['username']; 
?>
    <a href="#"><?php echo $username ?></a>
<?php
}
?>

You need to get the user name for each item in the row.

Upvotes: 0

Orville Patterson
Orville Patterson

Reputation: 524

$result = mysqli_query($mysqli,"SELECT username FROM members");
 $count=0;

while($row = mysqli_fetch_array($result)){

 array[$count]['Rkey'] = $count;
 $array[$count]['username']= $row['username'];
 $count++;

}

 mysqli_free_result($result);
    }

to print the values

$res_count= count($array);

for ($x=0;$x<$res_count;$x++)
{
  echo $array[$x]['username'];
  }

Upvotes: 0

Charles Harmon
Charles Harmon

Reputation: 380

Because you're only getting the first result. Try:

$users = array();
$result = mysqli_query($mysqli,"SELECT username FROM members");
while($row = mysqli_fetch_assoc($result)){
  $users[] = $row['username']; 
}

<?php 
foreach ($users as $user): ?>

<a href="#"><?php echo $user; ?></a>
<?php endforeach; ?>

Upvotes: 1

Related Questions