I want to select all of the usernames. I tried to do SELECT username FROM members and then mysql_fetch_array. So I would do $data["username"]. But I also want to select each row individually. Any help on how to do this would be helpful thank you.
Asked
Active
Viewed 1.2k times
2
-
I'm not sure I'm clear on what you're trying to get an answer to. Running that SELECT statement into a while loop would supply you with each row from the database - so, what's the actual problem or what are you trying to accomplish? – Drew Sep 05 '12 at 23:31
-
Wait what? It would be able to select each if I simply loop it? – Aurange Sep 05 '12 at 23:32
-
Yes - running it through while ($data = mysql_fetch_assoc($query)) {} would run through every row that you've selected – Drew Sep 05 '12 at 23:33
-
1@auragar [Read this](http://stackoverflow.com/questions/8347565/difference-between-mysql-fetch-array-and-mysql-fetch-row) to find out the difference. – Kermit Sep 05 '12 at 23:36
-
Basically for me the difference between how I use array and how assoc works is none. However array also works like row, in that I can use numbers instead. – Aurange Sep 05 '12 at 23:50
3 Answers
4
Use PDO for that.Example of using PDO
<?php
$stmt = $dbh->prepare("SELECT username FROM members");
if ($stmt->execute(array($_GET['username']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
John Woo
- 258,903
- 69
- 498
- 492
-
PDO? I never heard of this. Also I am not using GET data, but thank you. So where would I learn more about this PDO. – Aurange Sep 05 '12 at 23:39
-
@auragar sorry i wasn't able to include the link. [So here it is](http://php.net/manual/en/book.pdo.php) – John Woo Sep 05 '12 at 23:50
-
@auragar and others. PDO and MySQLi are recommended by PHP, while mysql_* functions are deprecated. PDO has the advantage that it works with all the major databases and more, it provides prepared statements which are the default way to work for most professionals and helps prevent most if not all sql injection security holes by allowing you to separate the SQL from the variables. – Timo Huovinen Oct 19 '13 at 17:57
1
Loop through all results with while()
$result = mysql_query('SELECT username FROM members');
while ($username = mysql_fetch_assoc($result)){
echo $username['username']; //this will go for every result, so every row in the database
}
Rene Pot
- 24,681
- 7
- 68
- 92
-
2
-
-
2
-
exactly, mysql_functions are deprecated. It is advised to use PDO or mysqli functions instead – Hugo Dozois Sep 05 '12 at 23:34