带有动态值的空SUM()

时间:2013-03-01 07:01:26

标签: php mysql

如果我用244替换第一个%s,我得到的总和没有任何问题。但是当在这种情况下使用动态值$ shot时,它似乎没有得到任何东西,我的查询也没有失败,因为其他结果都很好(例如stories.id,stories.title)。

$query = sprintf("
SELECT 
stories.id, 
stories.title,  
stories.timestamp, 
stories.text, 
users.name, 
users.avatar, 
users.id AS idus,
(SELECT sum(reviews.amount) FROM reviews WHERE reviews.storyid='%s') AS reviews 

FROM stories INNER JOIN users ON stories.uid=users.id WHERE stories.id = '%s'",
    mysql_real_escape_string($shot),
    mysql_real_escape_string($shot));

射击来自这里:

$shot = $_GET['shot'];      

3 个答案:

答案 0 :(得分:1)

我会写这样的东西。

SELECT 
stories.id, 
stories.title,  
stories.timestamp, 
stories.text, 
users.name, 
users.avatar, 
users.id AS idus,
SUM(reviews.amount) as reviews
FROM stories 
INNER JOIN users ON stories.uid=users.id 
INNER JOIN reviews ON stories.id = reviews.storyid
WHERE stories.id = '%s'"

这与您的问题无关,但与优化有很大关系。

答案 1 :(得分:0)

鉴于id始终是数字,

Make $shot = (int)$_GET['shot'];(%d说明符将变量视为整数,但您可能需要在其他地方使用它。)

然后替换:

带有reviews.storyid='%s'

reviews.storyid=%d

带有WHERE stories.id = '%s'

WHERE stories.id = %d

无需执行mysql_real_escape_stringwhy?)。

答案 2 :(得分:0)

在执行查询之前,请使用

进行打印
echo $query;

看看结果是什么,如果它不是你把手动值放在你需要改变它的时候。

我建议使用。

$shot = mysql_real_escape_string($shot);
$query = "SELECT 
stories.id, 
stories.title,  
stories.timestamp, 
stories.text, 
users.name, 
users.avatar, 
users.id AS idus,
(SELECT sum(reviews.amount) FROM reviews WHERE reviews.storyid='" . $shot . "') AS reviews 

FROM stories INNER JOIN users ON stories.uid=users.id WHERE stories.id = '" . $shot . "'";