tags:

views:

58

answers:

2

I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?

Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!

+3  A: 
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) { 
    echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan
Beat me to the submit button. This will do it for you.
mjboggess
A: 

halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:

SELECT username, name
FROM sometable
WHERE (username = 'johndoe');

This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:

$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
    if ($row['username'] == 'johndoe') {
        // do something, this is a row you want
    } else {
        // not a row you want. ignore it, or deal with it some other way
    }
}

the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.

Marc B