0

I've been trying to change some code for a validation script so that it doesn't include goto, as I want to run my scripts on a webhost, and unfortunately most of them don't really have 5.3 or later.

The code is meant to use a value generated by rand for a unique validation number. If it finds it already in the DB, it will append 1 on to the number as many times as it needs to until it finds a usable number. Pretty straightforward. I know it's terrible practice for a MySQL query, but it's really just a simple script for practice.

The code is as follows:

function gen_val($val)
{
    $query = mysql_query("SELECT val_id FROM users_tmp WHERE val_id=$val");
    $row = mysql_fetch_array($query);
    if ($row[0]==$val) {
        gen_val($val+1);
    } else {
        return $val;
    }
}

$val_x=gen_val(rand());

This returns a value '0' if the value already existed in the DB. Function works fine if there's no similar value already, so I think there's a problem with the function recursing. I don't think I really know how to use it properly, so please go ahead and educate me.

Cheers.

Asher

1
  • 1
    Just FYI as your database grows this particular function is going to get slower and slower. MySQL has unique id functionality built in, this is unnecessary. Commented May 8, 2011 at 6:09

2 Answers 2

2

You forgot to return the result of your recursion.

return gen_val($val+1);
Sign up to request clarification or add additional context in comments.

4 Comments

It does return the value on only the last iteration of the recursion that meets the if condition, but every subsequent completion, the return value is not returned including the first iteration of calling gen_val.
Because recursion doesn't always involve returning something.
It returns $val because you wrote return $val. It does not return $val on its own.
Because those are two independent function calls.
1

Correct me if I'm wrong, but you want to get a unique ID for each user. MySQL has this feature.

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.