开发者

Replacing goto with a function, why doesn't this work?

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 numbe开发者_开发知识库r. 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


You forgot to return the result of your recursion.

return gen_val($val+1);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜