在mysql查询中使用GROUP_CONCAT时出错

时间:2014-06-09 01:08:29

标签: php mysql sql

我的代码运作良好,但是当我添加

GROUP_CONCAT(CONCAT("<a href='index.php?id=", awards_user.userid, "'>", awards_user.username, "</a>")) AS userlist

使用用户名获取用户ID,显示错误

解析错误:语法错误,意外T_STRING [在此行]

SELECT awards.name as name, awards.link as link, 
       GROUP_CONCAT(DISTINCT awards_user.username) AS username,
       GROUP_CONCAT(DISTINCT awards_user.userid) AS userid,
       GROUP_CONCAT(CONCAT("<a href='index.php?id=", awards_user.userid, "'>", awards_user.username, "</a>")) AS userlist
   FROM awards LEFT JOIN awards_user ON (awards_user.awardid = awards.awardid)
   where awards.forumid = '".$_REQUEST['forumid']."'
   GROUP BY awards.awardid, awards.name, awards.link

2 个答案:

答案 0 :(得分:0)

你应该用反斜杠"来转义双引号\,否则php会把它理解为字符串的结尾:

$sql = "SELECT awards.name as name
             , awards.link as link
             , GROUP_CONCAT(DISTINCT awards_user.username) AS username
             , GROUP_CONCAT(DISTINCT awards_user.userid) AS userid
             , GROUP_CONCAT(CONCAT(\"<a href='index.php?id=\", awards_user.userid, \"'>\"
             , awards_user.username, \"</a>\")) AS userlist
        FROM awards LEFT JOIN awards_user ON (awards_user.awardid = awards.awardid)
        WHERE awards.forumid = '" . $_REQUEST['forumid'] . "'
        GROUP BY awards.awardid
               , awards.name
               , awards.link";

答案 1 :(得分:0)

报价的转出是一个问题。那么为什么不这样使用heredoc syntax

$formid = $_REQUEST['forumid'];

$query = <<<EOT
SELECT awards.name as name, awards.link as link, 
       GROUP_CONCAT(DISTINCT awards_user.username) AS username,
       GROUP_CONCAT(DISTINCT awards_user.userid) AS userid,
       GROUP_CONCAT(CONCAT("<a href='index.php?id=", awards_user.userid, "'>", awards_user.username, "</a>")) AS userlist
   FROM awards LEFT JOIN awards_user ON (awards_user.awardid = awards.awardid)
   where awards.forumid = '$formid'
   GROUP BY awards.awardid, awards.name, awards.link
EOT;

这个想法是heredoc语法允许带有字符串替换的完整字符串&amp;无需担心转义报价。或者您知道可以为"<a href='index.php?id="'></a>设置变量,如下所示:

$formid = $_REQUEST['forumid'];

$id_link_1 = "<a href='index.php?id=";
$id_link_2 = "'>";
$id_link_3 = "</a>";

$query = <<<EOT
SELECT awards.name as name, awards.link as link, 
       GROUP_CONCAT(DISTINCT awards_user.username) AS username,
       GROUP_CONCAT(DISTINCT awards_user.userid) AS userid,
       GROUP_CONCAT(CONCAT($id_link_1, awards_user.userid, $id_link_2, awards_user.username, $id_link_3)) AS userlist
   FROM awards LEFT JOIN awards_user ON (awards_user.awardid = awards.awardid)
   where awards.forumid = '$formid'
   GROUP BY awards.awardid, awards.name, awards.link
EOT;