-1

I have the following recursive function that won't return anything if it has to loop once. I can echo the username in the return condition and it shows the correct username after the loop, with an appended number (e.g. jdoe_45), but it doesn't return it.

function createUsername ($conn, $firstname, $lastname, $numerate = false) {

    $fn = preg_replace("/[^A-Za-z0-9 ]/", '', $firstname);
    $ln = preg_replace("/[^A-Za-z0-9 ]/", '', $lastname);

    $arg = ($numerate) ? '_' . rand(11, 99) : '';

    $username = strtolower(substr($fn, 0, 1) . $ln . $arg);

    $sql = "SELECT * FROM users WHERE username = '$username'";
    $rs  = mysql_query($sql, $conn) or die ("Could not execute query.");
    $num = mysql_numrows($rs);

    if ($num == 0) {

        return $username;
    }

    createUsername($conn, $firstname, $lastname, 1);
}
Mike B
  • 31,886
  • 13
  • 87
  • 111
drpudding
  • 159
  • 4
  • 14

2 Answers2

0

You forgot to fetch your results:

if ($num == 0) {
    $row = mysql_fetch($rs);
    $username = $row['username'];
    return $username;
}
glomad
  • 5,539
  • 2
  • 24
  • 38
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • OMG! That wins as my best oversight of the 2013. Thanks. – drpudding Jan 16 '13 at 02:12
  • If you have no rows returned (`$num == 0`), fetching the data won't do you any good. – Marc Baumbach Jan 16 '13 at 02:13
  • Right. I just realized that doesn't matter. I'm not trying to return data from the db. I'm just testing if the user is already present. So why isn't this working, and is not returning the username I constructed. So why isn't this working? Nothing is returned, despite that the username is passed into the condition. – drpudding Jan 16 '13 at 02:55
0

You need to return your recursive call as well:

return createUsername($conn, $firstname, $lastname, 1);

Currently, you only return when $num == 0.

Marc Baumbach
  • 10,323
  • 2
  • 30
  • 45