php - 您的 SQL 语法有误;

标签 php mysql zend-framework mysql-error-1064

我的代码到目前为止

        $limitText ="";
        if($history_length){
            $limitText = ' limit '. $history_length;
        }

        if(!$history_days){
            $history_days = '180';
        }
$db = $this->getInvokeArg('bootstrap')->getPluginResource('db')->getDbAdapter();
        //changing code to add min(currBalance) -- as sum(points) is valid only for debit. Also sort by desc instead of  (major bug)
        $history_stmt = $db->query("SELECT sum(points) as points,credit_date,min(currBalance) as currBalance,extRefId,transactedAt,pointType FROM credits where userid = '".$userid."' and credit_date >= date('now','-".$history_days." days')  group by extRefID,pointType order by creditid desc ".$limitText);
        $history_results = $history_stmt->fetchall();

        $expiry_stmt = $db->query("SELECT availablePoints,expiry_date FROM credits where userid = '".$userid."'and availablePoints > 0 and expiry_date <= date('now','+".$expiry_duration." days') order by expiry_date asc ");
        $expiry_results = $expiry_stmt->fetchall();

我遇到了一个错误

<b>Message:</b> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''-180 days')  group by extRefID,pointType order by creditid desc' at line 1  </p>

我能做什么我无法找到解决方案

最佳答案

似乎您正在使用 MySQL Date function以错误的方式 - 你真的打算使用 php date函数代替?而不是例如

"[...] credit_date >= date('now','-".$history_days." days')  group by [...]"

你必须写:

 "[...] credit_date >= '".date('-'.$history_days.' days')."' group by [...]"

只有变量(例如 $history_days)会在用双引号 (") 括起来的字符串中被 php 展开,而不是函数调用。如果你在字符串中包含函数调用,php 无法识别它,并且它将按原样传递给 mysql,而不是首先由 php 执行;但您希望 php 对其求值,因此您必须将它从字符串常量中排除,并使用连接运算符 (.) 将其添加到您的字符串中。

不过,您的 php 日期函数调用似乎也不正确;要获得“当前日期减去一定天数”,最好使用像这样的 mysql 日期函数:

 "[...] credit_date >= DATE_SUB(NOW(), INTERVAL '$history_days' DAY) group by [...]"

还有一个关于安全性的一般说明:从您提供的脚本中不清楚,但是如果 $history_days$history_length$user_id$expiry_duration(在 SQL 语句中使用的变量)只有极小的机会被用户设置,你不应该将它们直接插入到 SQL 语句中,但是do something to prevent SQL injection .

关于php - 您的 SQL 语法有误;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8472043/

相关文章:

PHP 警告 : Module already loaded in Unknown on line 0

找不到 mysql_upgrade

php - Zend Framework 中的嵌套 Controller

php - 使用 Zend (PHP) 在 Gmail 中包含客户的默认电子邮件签名

php - 使用 PHP HttpRequest 发送文件数据

php - PythonPATH 和 PHP

javascript - 将同步 firebase 函数重写为异步

php - 带有巨大表的嵌套 mysql 查询

php - 在 zend 框架中导出 csv

php - CodeIgniter is_unique 语言文件中的错误消息