Alex Rivera | Logout

Can I just SELECT one column in MYSQL instead of all, to make it faster?

Asked 2012-05-01T20:53:28.547
10

I want to do something like this:

$query=mysql_query("SELECT userid FROM users WHERE username='$username'");
$the_user_id= .....

Because all I want is the user ID that corresponds to the username.

The usual way would be that:

$query=mysql_query("SELECT * FROM users WHERE username='$username'");
while ($row = mysql_fetch_assoc($query))
    $the_user_id= $row['userid'];

But is there something more efficient that this? Thanks a lot, regards

Edit
Report

1 Answer

13

You've hit the nail right on the head: what you want to do is SELECT userid FROM users WHERE username='$username'. Try it - it'll work :)

SELECT * is almost always a bad idea; it's much better to specify the names of the columns you want MySQL to return. Of course, you'll stil need to use mysql_fetch_assoc or something similar to actually get the data into a PHP variable, but at least this saves MySQL the overhead of sending all these columns you won't be using anyway.

As an aside, you may want to use the newer mysqli library or PDO instead. These are also much more efficient than the old mysql library, which is being deprecated.

answered 2012-05-01T20:55:09.607

Your Answer