开发者

What's the most appropriate way to re-call a recursive function?

I've been told that authCode(); isn't being re-called in the most efficient way, as it will "stack a lot of DB connections, opening and closing them quickly which is expensive in respect to resources".

Here's my code:

function authCode() {

$num1 = mt_rand(1, 2147483647);
$num2 = mt_rand(1, 2147483647); 
$authcode = dechex($num1).dechex($num2);;

include("../db/71cfde725dc86.php");

$conn = mysql_connect($db_host, $db_uname, $db_pword) or die("Couldn't connect because ".mysql_error()); mysql_select_db($db_name);
$query = "SELECT COUNT(*) FROM records WHERE valcode='$authcode'";
$result = mysql_query($query) or die("SELECT query failed due to ".mysql_error());

$count = mysql_fetch_assoc($result);
$row = $count['COUNT(*)'];

if($row > 0)
{
    $authcode = authCode();
}
else 
{
$query2 = "INSERT INTO records (valcode) VALUES ('$authcode')";
$result2 = mysql_query($query2) or die("INSERT query failed due to ".mysql_error());
}

mys开发者_JAVA技巧ql_close($conn);

return $authcode;
}

authCode();

I'm focusing on $authcode = authCode(); and the fact that the database connection isn't closed until the end, which means if it does re-call the connection is still open (so I have heard)?

Should I close the connection after $row is assigned, and then re-open and close within the else statement?


What you should be doing is opening the connection before the first call to authCode(), and passing it in as a parameter. That way you use a single connection for all calls.


There's absolutely no need to run this function recursively. It can be done far easier with less overhead using a simple while loop. In pseudo code:

function authCode() {
    ... connect to database ...
    while (true) {
       ... generate random code ...
       if (code is in database) {
           continue;
       } else {
          insert code into data base
          break;
       }
    }
    return $code
}

No recursion, one single database handle.

And beyond this, why such a lousy code generator? You'll get a variable-length code, with high chance of collisions. Why not simply use sha1 with a properly salted source string, which is far far less likely to be collide than your version. Your code has a theoretical keyspace of 32 bits, while md5 is 128bit and sha2 is 160bit.


You could pass your database connection in the function :

function authCode($conn) {
    if ($db_link == null) {
        $has_instantiated_connection = true;
        // set the connection
    }
    else
        $has_instantiated_connection = false;

    // stuff

    // recall
    authCode($conn)

    if ($has_instantiated_connection)
        // close the connection
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜