0

I am having trouble with the getNext() function...

If isTaken() == true, it does update last, but I'm not sure it is invoking the getNext() function as the function never returns $next.

If isTaken() == false, $next is returned.

Any ideas?

function isTaken ($id){
  $sql = "SELECT asset_no FROM tb_asset WHERE asset_no='" . $id . "'";
  $result = mysql_query($sql) or die(mysql_Error());
  if (mysql_num_rows($result)) return true;
  else return false;  
  mysql_free_result($result);
}


function getNext(){
  $sql = "SELECT last FROM app_asset";
  $result = mysql_query($sql) or die (mysql_error());
  $last = mysql_fetch_array($result);
  mysql_free_result($result);

  $next = ++$last['last'];

  if (isTaken($next)){
    $sql = "UPDATE app_asset SET last='" . $next . "'";
    mysql_query($sql) or die (mysql_error());
    getNext();
  } else {  
    return $next;
  }
}
3
  • Please don't use mysql_query. It's deprecated and insecure. Commented Nov 16, 2013 at 21:19
  • @MattDiamant what do you suggest...mysqli? Or are you refering to the way mysql_query is used? Commented Nov 16, 2013 at 21:36
  • 1
    @Mike PDO or MySQLi are the usual replacements. See this tutorial or this page in the manual for more information Commented Nov 16, 2013 at 21:42

2 Answers 2

1

As Sable Foste pointed out, you will always need a return statement. In your case however, it looks like your code needs to be modified to

if (isTaken($next)){
    //code
    return getNext();
} else
    return $next;

So the function will stop the recursion and return once isTaken($next) is false

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

Comments

0

You need to pass the variable back to the function:

  if (isTaken($next)){
    $sql = "UPDATE app_asset SET last='" . $next . "'";
    mysql_query($sql) or die (mysql_error());
    getNext();
    return $next; // this line added.
  } else {  
    return $next;
  }

3 Comments

Actually this could be simplified to if (..) {...} return $next; (since both cases of the if have the same return statement), but you made your point clear.
That does not work. I can only return $next when isTaken() == false. In your answer $next is returned before the function is finished and returns a result that is taken.
@Mike, because this is a recursive array, you need to return something on every recursion. Otherwise, you will only get the final result if no recursion occurs. If not $next, then use a different value to return.

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.