我有一个很长的查询
$s = $dbh->prepare("SELECT name,type,
(select count(opinionid) from fe_opinion where actor=name) as countopinion,
(select count(commentid) from fe_comment where actor=name) as countcomment,
(select count(commentid) from fe_reply where actor=name and replyto<>null) as countreply,
(select count(voteid) from fe_vote where actor=name and replyto<>null) as countvote,
(select count(voteid) from fe_vote where actor=name and replyto<>null and vote=1) as countagree,
(select count(voteid) from fe_vote where actor=name and replyto<>null and vote=0) as countdisagree
from fs_actor where name=:name");
当我在多行中这样写它时,它给了我一个语法错误。我不确定编译器,因为我没有执行它。是应该以这种格式工作还是应该使用heredoc?
如何从下一行继续写一个字符串?应该通过按Enter键继续下一行吗?我应该使用heredoc还是有特殊的新行字符?
我在phpdoc
中找到了这个例子echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
所以现在我觉得我的语法错误是别的。
答案 0 :(得分:2)
这里只是一个黑暗的镜头,你确定它不是countdisagree
之后的最后一个逗号,它会给你一个语法错误吗?在SELECT的最后一部分之后你没有放一个逗号,你可能没有意识到你把它放在那里,我知道在分解一个长的SQL查询时我自己做了很多,它会给出一个语法错误,如果它存在,因为它期望另一个语句可供选择。
SQL查询,多行或其他方式,如果确实存在语法错误,则应该只提供语法错误,因此如果您遇到语法错误,您可以打赌您有一个语法错误。你可以打破它,这样你每行只有一个单词,它不会给出语法错误。
答案 1 :(得分:1)
PHP中没有行继续符。你应该使用Heredoc:
$s = $dbh->prepare(<<<'EOQ'
SELECT name, type,
(SELECT COUNT(opinionid) FROM fe_opinion WHERE actor = name) AS countopinion,
(SELECT COUNT(commentid) FROM fe_comment WHERE actor = name) AS countcomment,
# ...
FROM fs_actor WHERE name = :name"
EOQ
);
EOQ
周围的单引号是PHP莫名其妙地调用"Nowdoc"语法,与Heredoc相同但未解析 - 相当于使用$s = 'Hello $world';
vs.双引号$s = "Hello $world";
- 这可能会在某个地方节省几毫秒(但顺便说一下,似乎会抛弃SO的语法高亮)。
PHP中唯一的(合理的)替代方法 - 除了将查询存储在别处之外 - 是使用字符串连接,这非常难看:
$s = $dbh->prepare(
'SELECT name, type, ' .
' (SELECT COUNT(opinionid) FROM fe_opinion WHERE actor = name) AS countopinion, ' .
' (SELECT COUNT(commentid) FROM fe_comment WHERE actor = name) AS countcomment, ' .
// ...
' FROM fs_actor WHERE name = :name'
);
......这非常难看,需要你注意你的空间。