0

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:-

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

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:-

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);
    }
}
3
  • 3
    upload the code of Get_Val() Commented Apr 8, 2012 at 17:23
  • Also try if(isset($val)). Are you sure Get_Val() is returning a value? Commented Apr 8, 2012 at 17:24
  • make sure you sanitize $_POST['val'], or else, sql injection is positive Commented Apr 8, 2012 at 17:43

1 Answer 1

0

Get_Val does not return a value if $count == 0. Add a return statement before the recursive call. Like this:

...
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'
    {
       return Get_Val($sid, $a,$link);
    }
}
...
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.