PHP code execution sequence
<p>I am trying to execute some lines of php code, but it seems that tey are not being execute in the required order. Here is a code snippet:- </p>

<pre><code>if( !empty($_POST['val']) )
               {
                    $val = Get_Val($sid, $_POST['val'], $lnk);
                    if($val)
                    { 
                        echo "&lt;br /&gt;Here Value : " . $val;
                    }
                    else
                    {
                        echo "Invalid Value.";
                    }
              }
</code></pre>

<p>When I echo the value before returning in function Get_Val() it shows a positive number for some set of valid arguments, which means that the If-condition is true, but when I execute the code the Else part is being executed. Though the output appear in order, they are not consistent. I hope I have made the problem clear. 
Any amount of help is appreciated. Thanks! 
Here is Get_Val() function:-</p>

<pre>
function Get_Val( $sid, $a, $link)
{
    //check is name is already present in table 
    $query = "SELECT val FROM store WHERE name = \"" . $a . "\"";  //val is auto incremented in sql
    $result = mysql_query( $query ,$link ) or die( mysql_error());
    if($result)
    {   
        $count = mysql_num_rows($result);
        if( $count == 0 ) //insert name and the return val
        {
            $query_x = "INSERT INTO store(name) VALUES('" . $a . "')";
            $result = mysql_query( $query_x ,$link ) or die( mysql_error());
            if($result)//If new name inserted then return the 'val'
            {
            Get_Val($sid, $a,$link);
            }
        }
        else
        {
            $row = mysql_fetch_assoc( $result );
            echo "Val in Get_Val : " . $row['val'];
            return $row['val'];
        }
    }
    else
    {
        echo "Unexpected Error Occured...!!!";
        exit(0);
    }
}</pre>
