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.
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; ?>
$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'];
}
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.
链接地址: http://www.djcxy.com/p/75308.html上一篇: 如何获得准确相关的搜索结果
下一篇: 未能从表格中获取所有用户名