View Full Version : Echo is printing twice

02-01-2010, 08:11 AM
What am I doing wrong. I have a foreach loop that multiplies a variable times a constant and then echo the result. but the result is printing twice.

mysql_select_db($database_connifq, $connifq);
$query_quotapounds = "SELECT * FROM quotapounds";
$quotapounds = mysql_query($query_quotapounds, $connifq) or die(mysql_error());
$row_quotapounds = mysql_fetch_array($quotapounds);
$starting_quota = $row_quotapounds;
foreach($starting_quota as $roll_over){
$roll_over_new = ($roll_over * 1.1);
echo "$counter, $roll_over, $roll_over_new <br>";

The output:

0, PN002, 0
0, PN002, 0
0, 0, 0
0, 0, 0
0, 21978, 24175.8
0, 21978, 24175.8
0, 6699, 7368.9
0, 6699, 7368.9
0, 33982, 37380.2
0, 33982, 37380.2

02-01-2010, 11:33 AM
that’s because mysql_fetch_array() returns the row numerically and associatively indexed by default. see mysql_fetch_array() (http://php.net/mysql-fetch-array)

02-01-2010, 02:08 PM
Dormilich is absolutely right. Just add the 2nd parameter MYSQL_ASSOC or MYSQL_NUM to mysql_fetch_array() to avoid this problem:

$row_quotapounds = mysql_fetch_array($quotapounds,MYSQL_NUM);

Also I see that you have a loop over table columns, not table rows. It could be that your table violates the 1st Normal Form and could require normalization ... Of course it is difficult to say more without actually seeing the table quotapounds structure and getting some explanation on how the table is used in the system.

Also (while this does not affect the current problem, but still ...) I would advise against using the so called "evil star" * in the query. It is always better to list the fields in a query explicitly.