-6

I have to append more values to the associative array, the values are getting overwritten and I can see only last value displayed.

My snippet is :

$sql= "SELECT  MONTHNAME(dt),SUM(dist) FROM demo GROUP BY MONTHNAME(dt) ";
$result=mysql_query($sql,$con) or die(mysql_error());

while($row = mysql_fetch_array($result))
{

$values=array($row['MONTHNAME(dt)'] => $row['SUM(dist)']);

}

I expect other values also to be present the array $values, but it is not happening.

Rikesh
  • 26,156
  • 14
  • 79
  • 87

3 Answers3

2

Seem you need to do something like this,

$values = array();
while($row = mysql_fetch_array($result))
{
  $values[$row['MONTHNAME(dt)']] = $row['SUM(dist)'];
}
print_r($values);

If you need an associative array than do like.

$values[] = array($row['MONTHNAME(dt)'] => $row['SUM(dist)']);

Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Rikesh
  • 26,156
  • 14
  • 79
  • 87
  • `$row['SUM(dist)']);` < brace ? – BlitZ Apr 30 '13 at 06:36
  • no its not like this, i have to store month name with total distance run in the month. For this i will need associative array.with the code:$values=array($row['MONTHNAME(dt)'] => $row['SUM(dist)']); i am able to store the values but it is showing me the last stored values only...i want the values of all the months which is there in my database.. – Shivani Sinha Apr 30 '13 at 07:25
  • @ShivaniSinha - yes . you can do either way. – Rikesh Apr 30 '13 at 07:31
1

Try this:

$values[$row['MONTHNAME(dt)']] = $row['SUM(dist)']
BlitZ
  • 12,038
  • 3
  • 49
  • 68
  • 1
    Please, consider usage of highlight options, when posting code. – BlitZ Apr 30 '13 at 06:35
  • I figured the purpose of highlighting was to distinguish code from not code. This the post had ONLY code, what is the purpose of highlighting? edit: I suppose there's also syntax coloring now –  Apr 30 '13 at 06:36
  • to make code **readable**. – BlitZ Apr 30 '13 at 06:37
  • the only difference from before and now is that the key is red. –  Apr 30 '13 at 06:38
  • 1
    is it more readable? _(spoiler) colors is metadata for reader (/spolier)_ – BlitZ Apr 30 '13 at 06:40
  • no, in my opinion, this single line of code is not more readable than it was before. –  Apr 30 '13 at 06:41
0

I think you should use.

$sql= "SELECT  MONTHNAME(dt),SUM(dist) FROM demo GROUP BY MONTHNAME(dt) ";
$result=mysql_query($sql,$con) or die(mysql_error());
$values = array();
while($row = mysql_fetch_array($result))
{

  $values[] = array($row['MONTHNAME(dt)'] => $row['SUM(dist)']);

}
Deval Shah
  • 1,094
  • 8
  • 22