1

I have searched, researched, cursed a lot and shouted at my computer screen repeatedly but nothing seems to work…

I have created the below function to query a mysql database against the current date. If the current date does not exist in the database, the previous days date is generated and the function calls itself again with the new date. This continues until a match is found at which point the function returns an array with the required data.

function getWeekNumber($dateToQuery) {
    $oneDay = 86400;
    $timestamp = $dateToQuery;
    $stringDate = date("d/m/y", $dateToQuery);

    include("inc/dbconx.php");
    try {
        $STH = $DBH->prepare("SELECT `Week_Commencing`,`Week_Number` FROM weeks WHERE `Week_Commencing` = ?");
        $STH->bindParam(1,$stringDate);
        $STH->execute();
    } catch (Exception $e) {
        echo "There was a problem retrieving data from the database";
        exit;
    }

    $result = $STH->fetch(PDO::FETCH_ASSOC);

    if ($result == FALSE) {
        $prevDay = $timestamp - $oneDay;
        getWeekNumber($prevDay);
    } else {
        $output = array("Week_Commencing" => $result['Week_Commencing'], "Week_Number" => $result['Week_Number']);
        var_dump($output);
        return $output;
    }
}

$weekNumber = getWeekNumber($serverTime);
var_dump($weekNumber);

Everything works and you will see where I have included var_dumps to check the results…

The var_dump within the else clause of the function outputs as expected:

array(2) {
    ["Week_Commencing"]=> string(8) "19/05/14"
    ["Week_Number"]=> string(1) "4"
}

However, when I call the function it always returns NULL.

Does anyone know why this is happening?

Thanks in advance

1
  • 2
    May I sugggest PAP - Professional Agressive Programming? Shouting the computer is only the entry level ... :) There is also ADD - Agression Driven Development. And there is a school of taught favoring Escalation over Exception handling. Commented May 25, 2014 at 20:03

2 Answers 2

5
return getWeekNumber($prevDay);
^^^^^^

The function is not magically going to return a value, even from a recursive call, without the return statement.

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

1 Comment

My life is now complete! Cheers buddy
0

The return statement is in the else block. It executes when $result is true. So the $result seems to be false. Always.

1 Comment

In that case there would be no var_dump and eventually the script would die with a stack overflow.

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.