0

I'm basically trying to simply select from a table into an array...and it's not working correctly.

I have the following query

$graph = mysql_query("SELECT MONTHNAME(dateadded) MONTH, COUNT(*) COUNT
FROM products
WHERE ((YEAR(dateadded)=2012) && (site_url = '$_GET[site_url_graph]'))
GROUP BY MONTH(dateadded)",$db);

and I need to the results to be in an array like this (can be long or short month name thats not the issue):

$data = array(
    'Jan' => 12,
    'Feb' => 25,
    'Mar' => 0,
    'Apr' => 7,
    'May' => 80,
    'Jun' => 67,
    'Jul' => 45,
    'Aug' => 66,
    'Sep' => 23,
    'Oct' => 23,
    'Nov' => 78,
    'Dec' => 6
);

I'm trying this but getting message that not an array:

$data = array();
while($graphData = mysql_fetch_array($graph)){
    $data[] = $graphData;
    }

I'm sure this is a simple fix but tearing hair out here!

1
  • have you tryed running the query in phpmyadmin? what error do you get? Commented Sep 30, 2012 at 8:19

3 Answers 3

2

To get your expected array, you need to change your code following way.

$data = array();
while($graphData = mysql_fetch_array($graph)){
    $data[$graphData['MONTH']] = $graphData['COUNT'];
}
Sign up to request clarification or add additional context in comments.

Comments

0
$graph = mysql_query("SELECT MONTHNAME(dateadded) MONTH, COUNT(*) COUNT
                      FROM products
                      WHERE ((YEAR(dateadded)=2012) && (site_url = '$_GET[site_url_graph]'))
                      GROUP BY MONTH(dateadded)",$db);

$data = array();
while(list($month, $count) = mysql_fetch_array($graph)) {
    $data[$month] = $count; 
}

So, basically this is the fast and breezy version of what you want. Notice the usage of list. Nice and readable.

Comments

-1

Maybe this is the problem:
"COUNT(*) COUNT"? Try to change it to COUNT(*)

2 Comments

No, the query is fine - the error I think is in the last part of question
What are you getting when 'print_r($graphData)'

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.