开发者

mySQL fetch column based on another column in PHP

I'm trying to write my first PHP script wi开发者_JS百科th 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!


$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'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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜