MySQL查询在db客户端上工作正常,但PHP给出了SQLSTATE [42000]错误

时间:2016-12-01 18:52:37

标签: php mysql database

我有点奇怪的情况。长话短说,我有一个MySQL查询,当PHP运行它时,它给出了

  

警告:PDOStatement :: execute():SQLSTATE [42000]:语法错误或   访问冲突:1064您的SQL语法有错误;检查   手册,对应右边的MySQL服务器版本   在第6行''附近使用的语法。

但是,当我在DataGrip或SequelPro等数据库客户端应用程序上运行它时,它工作正常并返回行集。

echo $sQuery; // I print the query right before the execution
$stmt = $dbh->prepare ($sQuery);
$stmt->execute(); // This is the line that gives the error
$rResult = $stmt->fetchAll();
unset ($stmt); 

那么,你们之前有没有遇到过这种奇怪的问题,以及解决这个问题的最佳方法是什么?

QUERY:

SELECT SQL_CALC_FOUND_ROWS max(r.id) AS id
    ,r.client_name AS client_name
    ,r.ban_no AS ban_no
    ,r.ban_type
    ,(
        CASE 
            WHEN c.total_subscribers IS NOT NULL
                THEN c.total_subscribers
            ELSE r.subscribers
            END
        ) AS subscribers
    ,r.deal_value
    ,(
        CASE 
            WHEN c.potential_renewals IS NOT NULL
                THEN c.potential_renewals
            ELSE r.potential_renewals
            END
        ) AS potential_renewals
    ,r.prev_sales_rep_id
    ,r.sales_rep_id
    ,r.city
    ,ce.postal_code AS postal_code
    ,r.outlet_id
    ,(
        CASE 
            WHEN (
                    IFNULL(r.activity_type, 0) != '0'
                    AND IFNULL(r.activity_type, 0) != '4'
                    AND IFNULL(r.activity_type, 0) != '5'
                    AND (r.last_spoken IS NOT NULL)
                    AND (to_days(r.last_spoken) + 15 > to_days(r.call_date))
                    )
                THEN 'Yes'
            ELSE 'No'
            END
        ) AS activity_type
    ,r.ban_type AS STATUS
FROM TableR r
LEFT JOIN (
    SELECT ban_id
        ,type
        ,date_added
        ,COALESCE(total_subscribers, 0) AS total_subscribers
        ,COALESCE(potential_renewals, 0) AS potential_renewals
    FROM TableCS cs1
    WHERE cs1.ban_id IN (
            '6375305622668619'
            ,'7852790096027066'
            )
    GROUP BY cs1.ban_id
    ) c ON r.ban_no = c.ban_id
LEFT JOIN TableCE ce ON r.ban_no = ce.ban_no
WHERE (r.ban_type != 'D')
    AND r.dealer_id = '15'
GROUP BY r.ban_no
ORDER BY `subscribers` DESC LIMIT 0
    ,50;

1 个答案:

答案 0 :(得分:0)

好的,

我无法弄清楚原因,但是,

$list_of_bansas_string .= '\''.$call_list_record[0].'\','; // we used single quote to solve the problem

这是第一个原因。所以使用单引号而不是双引号是安全的。

$list_of_bansas_string[strlen($list_of_bansas_string)-1] = '  '; // we can't assign empty string, we should put space on it 

从字面上看,PHP不允许我分配空字符。所以,我最终用空格替换它并且它起作用了。