Let's say I have a table in my MySQL database called 'Users', and that table has two columns called 'Username' and 'Password'. At one point I want to get all of the usernames, without the passwords. What I did was:
$query = mysql_query("SELECT Username FROM Users");
$result = mysql_fetch_array($query);
foreach($result as $r){
echo $r;
}
Now, I have only two entries in my Users table, let's say that they are just 'User1' and 'User2'. The code from above, instead of showing me both of them, just shows the first user. I can't understand why this happens or how to fix it. I've also tried altering the query by adding WHERE 1
at the end, but I get the same result.
On the other hand, when I run this query inside PhpMyAdmin, it returns both User1 and User2.
Any ideas? Thanks.
See this statement here,
$result = mysql_fetch_array($query);
You're fetching only one row from the result set. Loop through the result set using while()
loop to display all usernames, like this:
$query = mysql_query("SELECT Username FROM Users");
while($result = mysql_fetch_array($query)){
echo $result['Username'] . '<br />';
}
Sidenote: Don't use mysql_
database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli
or PDO
extension instead. And this is why you shouldn't use mysql_*
functions.