Jump to content

foreach giving odd output


tHud

Recommended Posts

What on earth am I doing wrong?

I just want

Jan = 25

Feb = 40

etc... but I am getting the extra values as seen in the bottom window.

 

Thanks for any help :)

 

 

Entire contents of MySQL table

jan | feb | mar | apr | may | jun | jul | aug | sep | oct | nov | dec

25  |  40 |  45  |  70 |  23  |  77 |  88 |  49  |  56 |  59 |  65  |  70

 

 

My foreach script

<?php
include("includes/connect.php");

$query = "SELECT * FROM `months`";
$result = mysql_query($query) or die("There was a problem with the query: " . mysql_error()); 


if (mysql_num_rows($result) > 0)
{
$res = mysql_fetch_array($result);

echo count($res)."<br><br>";  //gives 24! why?

foreach ($res as $month => $value)
  {
  print "$month = $value<br>";
  }


}
else { echo "No data found!"; }
mysql_free_result($result);
mysql_close($connection);
exit;
?>

 

Output...

24

 

0 = 25

jan = 25

1 = 40

feb = 40

2 = 45

mar = 45

3 = 70

apr = 70

4 = 23

may = 23

5 = 77

jun = 77

6 = 88

jul = 88

7 = 49

aug = 49

8 = 56

sep = 56

9 = 59

oct = 59

10 = 65

nov = 65

11 = 70

dec = 70

Link to comment
https://forums.phpfreaks.com/topic/206918-foreach-giving-odd-output/
Share on other sites

You are selecting * which is all columns.  What did you expect  :confused:

$query = "SELECT `Jan`, `Feb` FROM `months`";
// snip
$res = mysql_fetch_assoc($result);

 

EDIT:  I see, you want all, just not the numerical indexes.  Use mysql_fetch_assoc() or pass MYSQL_ASSOC flag to mysql_fetch_array()

Returns an array of strings that corresponds to the fetched row' date=' or FALSE  if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works). [/quote']

 

 

so you are using MYSQL_BOTH, but you want MYSQL_ASSOC,

so change

$res = mysql_fetch_array($result);

to

$res = mysql_fetch_array($result,MYSQL_ASSOC);

or

$res = mysql_fetch_assoc($result);

Yes, I did.

 

That's why I said....

 

Ah!

Thank you both :)

 

..and marked the topic as solved ;) ;) ;)

 

Thanks again though - the speed at which I have been helped here is amazing.

 

 

EDIT...

My  "I don't understand" was aimed at the post before yours - which originally had a different response to that which is now there.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.