Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty SUM() with dynamic value [closed]

Tags:

php

mysql

If I replace the first %s with just 244, I get the sum without any problems. But when using a dynamic value in this case $shot, it doesn't seem to get anything and neither my query fails as other results are fine (e.g. 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 is coming from here:

$shot = $_GET['shot'];      
like image 992
Max Avatar asked Nov 12 '22 10:11

Max


1 Answers

I would write something like this.

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'"

This has nothing to do with your question but a lot to do with Optimization.

like image 188
beck03076 Avatar answered Nov 15 '22 04:11

beck03076