1

I came across the following code while constructing a php file:

  $query="UPDATE EXPERTS SET ...";  
  $result=$db->query($query);         
      if ($result) 
      {     
        $query="UPDATE USERS SET ...";  
        $result=$db->query($query);     
        if ($result) 
        {       
          ...
        }
      }

My question is if the above nested query is acceptable since we use the same variable ($result). Of course, it works, however I am not sure if is there any case of creating unexpected results...

Thank you

4
  • 3
    One $result overwrites the other $result. If you're good with that, then OK. Commented Jan 28, 2015 at 15:12
  • Creating unexpected results....such as....? Commented Jan 28, 2015 at 15:12
  • No Worry, Your $result variable overwrite everytime Commented Jan 28, 2015 at 15:12
  • There's probably nothing of value to overwrite because an UPDATE query produces only true/false as its output. There's no result set in $result (unless you are using a strange custom class) Commented Jan 28, 2015 at 15:13

1 Answer 1

2

You can use Data Flow Anomalies for this:

Required terminology:

  • d($var) - Value assigned to $var or initialized.
  • r($var) - Value of $var read.
  • u($var) - Value of $var is undefined.

We wish to avoid the following patterns:

  • ur - A undefined value is read.
  • du - A variable which once had a value becomes undefined before it's read.
  • dd - A variable receives a new value before it's earlier value is properly used; this is probably what you're afraid of.

Now let's take a look:

$query="UPDATE EXPERTS SET ...";            
$result=$db->query($query);                        d($result)
if ($result)                                       r($result)
{     
    $query="UPDATE USERS SET ...";  
    $result=$db->query($query);                    d($result)
    if ($result)                                   r($result)
    {       
        ...
    }
}

You got two dr so we can safely assume that you got nothing to worry about; in both cases the values are assigned and read before being assigned again.

One might argue that you should make a single variable which's purpose is to indicate the result of a single query but that's up to you.

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

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.