0

Is there a way to do an if statement like this:

if ($password == mysql_query("SELECT password from member WHERE id = $id")) {

// f00

}

So what I mean is, if it is possible and/or good practice to have a short query in your if, instead of extracting it from your DB first.

Thanks!

4
  • You might want to consider, Not doing it like that. What if mysql_query fails? What happens then? I would move the query-execution above the if-statement. Commented Feb 9, 2011 at 22:49
  • You must parse result from query to array or object. Then check Commented Feb 9, 2011 at 22:51
  • 2
    you have a SQL-injection hole in that code, change WHERE id = $id" to WHERE id = '$id'" *(note the single quotes around $id, otherwise mysql_real_escape_string() will not protect you. Commented May 28, 2011 at 19:34
  • 1
    Why aren't people using PDO instead of the horribly dangerous mysql_query function? Commented Jan 22, 2012 at 3:27

3 Answers 3

1

mysql_query returns a resource so it wont work

Sign up to request clarification or add additional context in comments.

2 Comments

He knows that, he is wondering if there is a similar single-statement that will accomplish what he's after.
it was not clear to me, based on what he posted, that he knew it. Looking at the other answers\comments, I'm not the only one either.
0

I wouldn't recommend it. If there is an error in the SQL, if you can't connect to the server, if there are no rows returned, or if there are any other errors then you'd have some big problems.

Comments

0

Sure it's possible but it's not a good idea.

Consider if you were using a database abstraction layer instead of basic php_mysql like adodb

you could easily have:

   if($password == $DB->GetOne('Select password from member where id = '.$ID)){
        //do something
   }

However if the query failed or otherwise returned anything you were implicitly expecting you could have unforeseen errors.

You should encapsulate database output and database queries so that if they fail, they fail gracefully and do not have weird side effects that could be a pain to track down later.

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.