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.
-
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– Drew2012-09-05 23:31:21 +00:00Commented Sep 5, 2012 at 23:31
-
Wait what? It would be able to select each if I simply loop it?Aurange– Aurange2012-09-05 23:32:28 +00:00Commented Sep 5, 2012 at 23:32
-
Yes - running it through while ($data = mysql_fetch_assoc($query)) {} would run through every row that you've selectedDrew– Drew2012-09-05 23:33:35 +00:00Commented Sep 5, 2012 at 23:33
-
1@auragar Read this to find out the difference.Kermit– Kermit2012-09-05 23:36:34 +00:00Commented Sep 5, 2012 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– Aurange2012-09-05 23:50:44 +00:00Commented Sep 5, 2012 at 23:50
Add a comment
|
3 Answers
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);
}
}
?>
3 Comments
Aurange
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.
John Woo
@auragar sorry i wasn't able to include the link. So here it is
Timo Huovinen
@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.
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
}
4 Comments
Kermit
Please advise OP to stop using
mysql_ functions.Rene Pot
why is that then? mysql_ functions are not bad
John Woo
@RenePot accordinmg to the manual, it is already depreciated.
Hugo Dozois
exactly, mysql_functions are deprecated. It is advised to use PDO or mysqli functions instead
while($row = mysql_fetch_array($result))
{
echo $row['username'];
}
1 Comment
Kermit
You should advise OP to stop using
mysql_ functions.