0

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!

2 Answers 2

4
$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";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to the submit button. This will do it for you.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.