-2

I am trying to pull data from SQL database which match with input year and month. Below is the code for SQL query

 <?php

    class SelectAMonthGet extends ConnectDB {

    var $year;
    var $month ;

        function __construct($n){
            $this->year = $_POST['year'];
            $this->month = $_POST['AnalyzeEnterAreaMonth'];
    }


        function SelectAMonthGetData(){

            $sql = "SELECT * FROM wp_myexpenses WHERE YEAR(date) = '$year' AND MONTH(date) = '$month' order by date,id"; 

            $result = $this->connect()->query($sql);
            $numRows = $result->num_rows;

                if($numRows > 0) {

                    while ($row = $result->fetch_assoc()){

                    $data[] = $row;
                    }

                    return $data;
                }
        }

    }

    ?>

A connectdb function contains my database connection and I am extending that function for this SQL query. But somehow, the code is not recognizing the $_POST variables $year and $month. Above code not giving any result.

I tried to change the SQL query to

$sql = "SELECT * FROM wp_myexpenses WHERE YEAR(date) = '2019' AND MONTH(date) = '1' order by date,id";

and the code works fine. Not sure why the code is not working when I mention the variable. Can someone guide me here?

acr
  • 1,674
  • 11
  • 45
  • 77
  • 1
    You should use year and month as $this->year aтd this->month – splash58 Jan 08 '19 at 12:19
  • 3
    Possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Nick Jan 08 '19 at 12:21
  • See the duplicate. `$year` and `$month` are local to the constructor. You need to declare them as class variables and use `$this->year` as @splash58 said. – Nick Jan 08 '19 at 12:23
  • Year $year and $month are local variable. First assign some value to them before executing query. – Umar Abdullah Jan 08 '19 at 12:36

1 Answers1

0

In your code $year and $month are declared as a class variable, and hence you can access them using $this-> (see constructor).

But in your function SelectAMonthGetData in your query, you are using them without this, and hence they were not accessible. To solve this issue, you can use:

$sql = "SELECT * FROM wp_myexpenses WHERE YEAR(date) = '$this->year' AND MONTH(date) = '$this->month' order by date,id";

Or

$year = $this->year; $month = $this->month;
$sql = "SELECT * FROM wp_myexpenses WHERE YEAR(date) = '$year' AND MONTH(date) = '$month' order by date,id";
Tejashwi Kalp Taru
  • 2,994
  • 2
  • 20
  • 35