0

My MySQL Query is like this :

 $myquery= "`SELECT  `year`, 

        sum(case when `countrycode` = '$countryone' then `values` else 0 end) AS `$countryone`,
        sum(case when `countrycode` = '$countrytwo' then `values` else 0 end) AS `$countrytwo`

FROM   `$index`
GROUP BY `year`"; 

This Query has to return all the values of the column values for two unique countrycodes in two different columns.

Before using the variables. my query was like this, which returned right output.

     $myquery = "SELECT  `year`, 

        sum(case when `countrycode` = 'NPL' then `values` else 0 end) AS `NPL`,
        sum(case when `countrycode` = 'USA' then `values` else 0 end) AS `USA`

FROM   `gainfinal`
GROUP BY `year`
";

But after replacing the real values with the variables the Query didn't work. How can I make the first Query run well ?

1

2 Answers 2

1

use - '".$countryone."' instead of '$countryone' in the query as it will be treated as string.

Sign up to request clarification or add additional context in comments.

5 Comments

@ SGT, Still, It didn't work for me. Should I change AS $countryone to `".$countryone."' as well ? Or only change it and keep everything as it is.
I'm trying to convert the result into a JsonTable. I changed the code as $temp[] = array('v' => $r['".$countryone."']); $temp[] = array('v' => $r['".$countrytwo."']); Did I use the correct format or I made a mess out of it ?
if u r getting it as an array then json_encode would do the all work to convert it to json.or else just built an array and pass it to json_encode.
@ SGT, Isn't it possible to pass a variable inside $temp[] = array('v' => $r['".$countryone."']); $temp[] = array('v' => $r['".$countrytwo."']);where $countryone and $countrytwo are variables. I need the values of $counntryone and $countryone but it prints $countrycode and $countryone.
My problem is actually with the variables inside above two lines.
1

Problem is this :

AS `$countryone`,

when you pass this in SQL query, php would try to search and replace a value for $countryone...so i would suggest to hardcode it as below :

$myquery= "`SELECT  `year`, 
        sum(case when `countrycode` = '$countryone' then `values` else 0 end) AS $countryone, /* notice "`" is removed */
        sum(case when `countrycode` = '$countrytwo' then `values` else 0 end) AS $countrytwo  /* notice "`" is removed */
FROM   `$index`
GROUP BY `year`"; 

4 Comments

Thank you for the answer. It gave the right output but I nned to display the new column name as the value that has been passed in the variable.
@CivaBhusal : so $countryone has a value?
Yaa. $countryone has a value.
@CivaBhusal : try the updated query...just remove backtics from alias :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.