dth8312 2016-01-23 05:59
浏览 40
已采纳

为什么我的MySQL查询返回语法错误?

I can't for the life of me figure out why my query is returning an error. I am generating it with PHP.

$column = "display_name";
$criteria = "Steven";
$query = "
                SELECT
                    m.user_id AS id, m.email_address, m.display_name, m.status, UNIX_TIMESTAMP(m.join_date) AS join_date,
                    l.listing_id, COUNT(l.member_id) AS total_listings,
                    g.group_id AS group_id, g.title AS group_title
                FROM users AS m
                LEFT JOIN listings as l on m.user_id = l.member_id
                LEFT JOIN groups AS g on m.group_id = g.group_id";

            if($column == "display_name"){

                $query .= '
                WHERE m.display_name LIKE \'%'.$criteria.'\'%';

            } else {

                $query = "
                WHERE m.".$column." = '$criteria'";

            }

            $query .="
                GROUP BY m.user_id";

The above code produces the following:

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 '% GROUP BY m.user_id' at line 8

SELECT m.user_id AS id, m.email_address, m.display_name, m.status, UNIX_TIMESTAMP(m.join_date) AS join_date, l.listing_id, COUNT(l.member_id) AS total_listings, g.group_id AS group_id, g.title AS group_title FROM users AS m LEFT JOIN listings as l on m.user_id = l.member_id LEFT JOIN groups AS g on m.group_id = g.group_id WHERE m.display_name LIKE '%Steven'% GROUP BY m.user_id

I've tried using LIKE %$criteria% and LIKE '%$criteria%' and I have no idea why neither are working. Any ideas?

  • 写回答

2条回答 默认 最新

  • dongqiang2024 2016-01-23 06:06
    关注

    Because your query is being interpreted like this

    WHERE m.display_name LIKE '%text'%
    

    And here you are using single quote before % sign. It should be '%text%' instead of '%text'% there. Fix it like this

    $query .= '
                WHERE m.display_name LIKE \'%'.$criteria.'%\'';
    

    Better to use double quotes outside to remove all this confusions. Like this:

    $query .= "
                WHERE m.display_name LIKE '%$criteria%'";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测