0

This script works, but it gives a warning if there is no match found:

if (...)
    irrelevant...

elseif ($userId = mysql_result(
                     mysql_query("SELECT id FROM users WHERE mail = 'jhon@doe.com'")
                             , 0))
    echo $userId;

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

Is this 'good' php? Or do I have to tackle this another way?

Goal of the script: If there is a user with that mail, give its ID

SuperSpy
  • 1,324
  • 3
  • 13
  • 28
  • Split it up into two conditions with an `and`. But the overhead is why everyone uses convenient wrapper classes, or at least not the dated mysql_* functions. – mario Jan 29 '12 at 13:23
  • @mario: what are the alternatives for the dated functions? – SuperSpy Jan 29 '12 at 13:26
  • Commonly [PDO gets recommended](http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons) as most convenient. – mario Jan 29 '12 at 13:29

2 Answers2

2

That's pretty ugly, especially since you do not have any error handling etc.

Better create a function performing the check that returns the user id or NULL. Then you can use code like this:

elseif(($userId = get_userid_by_email('jhon@doe.com')) !== null)
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
2

To get rid of the warning, check that query produces a result:

if($result = mysql_query("SELECT id FROM users WHERE mail = 'jhon@doe.com'"))
{
    if ($userId = mysql_result($result, 0))
    {
        echo $userId;
    }
}

For more info, see mysql_result reference.

Paker
  • 2,522
  • 1
  • 16
  • 27