tags:

views:

119

answers:

4

Does the function add_new_user run the SQL INSERT query if it is inside the if clause?

I have the functions

function add_new_user ( $username, $email, $passhash_md5 )
{
    -- cut: database INSERT queries
    return 1;                                                                                                
}

I use the code above as

if ( validate( $username, $password, $email ) == 1 ) {
    if ( add_new_user ( $username, $email, $passhash_md5 )  == 1 ) {   
                // problem here
              -- cut
    }                                                                                                        
}

I asked this question because I am not sure why this handler always gives unsuccessful registraton notice. The two codes belong to the handler. The bug seems to be in the syntax of my code and perhaps in the use of if/else.

+4  A: 

Does the function add_new_user run the SQL INSERT query if it is inside the if -clause?

Yes

function foo() {
  echo 'A';
  return true;
}

function bar() {
  echo 'B';
  return false;
}

if ( foo() ) {
  if ( bar() ) {
    echo 'C';
  }
}
// Output: AB
Mike B
+3  A: 

Yes

The function first get's evaluated for it's return value.

After the return value is known, the return value is compared to the integer value 1.

Brian Gianforcaro
+1  A: 

Yes. Anything between the if ( and the ) { is run to see if it is true. You can do anything in here really.

Lucas Jones
+1  A: 

PHP has to evaluate the boolean expression in order to know if it will execute the block or not. So, to evaluate the "==" operator, it needs to evaluate both sides, including the function "add_new_user".

So, the answer is: yes, it will evaluate the function add_new_user AND it will execute the insert operation (unless you have some code inside add_new_user that will block this).

However, you are doing something that should be avoided when possible: you are using a condition with side-effects! This will give you headaches (for example, right now!).

Bruno Reis
Could you please clarify what you mean by side-effects. Your answer however suggests me that it is not needed to check if the function has been accessed. **I would still like to see if the query was successuful somehow.**
Masi
Side-effects are things like: writing to disk/streams/database, opening connections, etc. You should know which function have side-effects (add_new_user has one, for instance). Then, you must know that when you call these functions, the side-effect will occur. Your original question could be rephrased as: "will the side-effect get executed with this 'if' statement?". Sure, you HAVE to check if it was succesful, and your way of doing it is not bad. Just keep in mind what I said about side-effects. Google for "pure function" or "side-effect free function" for more info!
Bruno Reis