首页 > 解决方案 > 作为类函数一部分的 SQL 查询中的 PHP 变量未按预期工作

问题描述

我正在尝试从与输入年份和月份匹配的 SQL 数据库中提取数据。下面是SQL查询的代码

 <?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;
                }
        }

    }

    ?>

connectdb 函数包含我的数据库连接,我正在为这个 SQL 查询扩展该函数。但不知何故,代码无法识别 $_POST 变量 $year 和 $month。上面的代码没有给出任何结果。

我试图将 SQL 查询更改为

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

并且代码工作正常。当我提到变量时,不确定为什么代码不起作用。有人可以在这里指导我吗?

标签: phpmysqli

解决方案


在您的代码中$year并被$month声明为类变量,因此您可以使用$this->(请参阅构造函数)访问它们。

但是在您SelectAMonthGetData的查询函数中,您在没有 的情况下使用它们this,因此它们无法访问。要解决此问题,您可以使用:

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

或者

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

推荐阅读