php - 作为类函数一部分的 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";
并且代码工作正常。当我提到变量时,不确定为什么代码不起作用。有人可以在这里指导我吗?
解决方案
在您的代码中$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";
推荐阅读
- ffmpeg - 转换为 yuv422p 像素格式不正确
- php - 如果 PDO Fetch() 请求没有返回记录,则无法回显字符串
- reactjs - 在 Storybook 选择选项中导入道具
- nginx - Nuxt.js Full Static - 应用程序配置文件的存储位置
- r - 加载本地 .osm 文件以显示/绘制地图
- javascript - Moment.JS:fromNow() 更准确
- reactjs - 使用 Reacthookforms 和 Yup 动态禁用字段
- java - 使用压缩滚动的 logback zip 日志是否需要安装“zip”linux 实用程序?
- reactjs - 在 ReactJS 中,由于其奇怪的结构,在从 API 呈现数据时面临问题
- python - 写入docx时如何删除特殊字符?