0

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.

  • There is nothing wrong with the query. `mysql_fetch_array` returns a row at a time and you need to iterate over it . – algrebe Sep 18 '16 at 13:52
  • Every time you use [the `mysql_`](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) database extension in _meow_ code **[a Kitten is strangled somewhere in the world](http://2.bp.blogspot.com/-zCT6jizimfI/UjJ5UTb_BeI/AAAAAAAACgg/AS6XCd6aNdg/s1600/luna_getting_strangled.jpg)** it is deprecated and has been for years and is gone for ever in PHP7. If you are just learning PHP, spend your energies learning the `PDO` or `mysqli` database extensions. [Start here](http://php.net/manual/en/book.pdo.php) – RiggsFolly Sep 18 '16 at 13:56

1 Answers1

1

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.

Community
  • 1
  • 1
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37