Forum Moderators: coopster

Message Too Old, No Replies

Getting user ID from MySQL by using username?

         

Dreap

6:06 pm on Apr 13, 2010 (gmt 0)

10+ Year Member



$username = someone

$query = mysql_query("SELECT user_id FROM users_table WHERE user_name LIKE '%$username%'") or die(mysql_error());

echo "Username ID is {$query}"


I want to make it query by username what's that persons user id and echo it. How can I do that? above script doesn't seem to function.

Readie

6:12 pm on Apr 13, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Right, first of all, we don't want to use "WHERE LIKE" - 2 users:

Tom
Tomcat

Tom will match both records.

$sql = 'SELECT user_id FROM users_table WHERE user_name = "' . mysql_real_escape_string($username) . '"';
$result = mysql_query($sql) or die('Error connecting to database');
$user_id = mysql_result($result, 0, "user_id");

echo 'Username ID is ' . $user_id;

Dreap

6:32 pm on Apr 13, 2010 (gmt 0)

10+ Year Member



Thanks Readie,

It worked.

rocknbil

6:37 pm on Apr 13, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



. . . and be sure to thoroughly cleanse the user name prior to writing it, trimming off leading/trailing spaces, allow only specific characters, etc . . . it will avoid annoying tech support emails. :-)

Dreap

7:56 pm on Apr 13, 2010 (gmt 0)

10+ Year Member



Aight, rocknbil.

Can use somehow AND in there aswell to specify which row I want?

$sql = 'SELECT user_period FROM users_table WHERE user_name = "' . mysql_real_escape_string($username) . '" AND user_color = "yellow"';
$result = mysql_query($sql) or die('Error connecting to database');
$user_period = mysql_result($result, 0, "user_period");


above code doesn't seem to work. Error is

Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 8 in /home/..

Readie

8:05 pm on Apr 13, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That's because there's no match. What you really need to do is this:

$sql = ...
$result = mysql_query($sql);

if(mysql_fetch_array($result)) {
$someVariable = mysql_result($result, 0, "some_column_name");
} else {
// No rows of data
}