1

I'm trying to fetch an array from a MySQL database but I can't when using a php variable ($final_date) instead of a string (2015-02-16). Can anyone help me?

Here is the code:

$date = new DateTime(date("Y-m-d"));
$date->modify('-1 day');
$prev_date = $date->format('Y-m-d');
$final_date = (string)$prev_date;

function GetPrevUsers(){
    $Adname = "Error";
    $query = mysql_query("SELECT users FROM stats WHERE date = '".$final_date."'");
    while($row = mysql_fetch_array($query)){
        $Adname  = $row['users'];
    }
    return $Adname ;
}

echo GetPrevUsers();

For some reason it the function works when I use the actual date instead of the php variable like this:

$query = mysql_query("SELECT users FROM stats WHERE date = '2015-02-16'");
2
  • Try echoing your query to make sure it is correct. Also, it is better to send $final_date as a parameter with you GetPrevUsers() function. Commented Feb 17, 2015 at 14:59
  • The query was right, but as you said I had to send $final_date as a parameter. Thanks! Commented Feb 17, 2015 at 15:06

2 Answers 2

2

It doesn't work as the scopes are different; you try to access a variable from within your function. You could either pass the variable to the function [e.g. : function GetPrevUsers($final_date){ yourCode }] , or add the variable $final_date to the $GLOBALS array.

The first approach is generally the preferred one; only add variables to the $GLOBALS array when it's really neccessary.

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

1 Comment

Solved! Thanks a bunch! I will mark your answer as correct when the time limit is over.
1

Keep $final_date as global, check function:

function GetPrevUsers(){
    global $final_date;
    $Adname = "Error";
    $query = mysql_query("SELECT users FROM stats WHERE date = '".$final_date."'");
    while($row = mysql_fetch_array($query)){
        $Adname  = $row['users'];
    }
    return $Adname ;
}

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.