Jump to content

Foreach giving more rows han expected


jocast

Recommended Posts

Hello, this is my first post in this forum, in fact my first post about php.

I am developing a crud application, but when i am trying to list a set of results it gives me more that the expected

Let me explain.

if i print_r my array (which i get it from a sql result) it gives me this

Array ( [0] => SHR1 [codprod] => SHR1 [1] => REGULAR SERVICE HOUR [proddescription] => REGULAR SERVICE HOUR [2] => 3.00 [qty] => 3.00 [3] => HR

 => HR [4] => 45.0000 [price] => 45.0000 [5] => 0.00 [discount] => 0.00 [6] => 135.00 [amount] => 135.00 ) 

if I  foreach($detailrow as $value){
            echo $detailrow['codprod'] . ", " .
                $detailrow['proddescription'] . ", " .
                $detailrow['qty'] . ", " .
                $detailrow['code'] . ", " .
                $detailrow['price'] . ", " .
                $detailrow['discount'] . ", " .
                $detailrow['amount'] . "<br/>";
       }
It gives me 14 rows with the same info. I run the query in mysql and it gives me only 1 result as expected. I noticed that the 14 rows are the same quantity of items in the array not results but let say columns, i dont know if it has something to do with the results. 
My questions:
Why it is giving me 14 rows instead just one?
What is the $value in the foreach function? why can't i just say foreach($myarray)?
why the print_r shows me the items array duplicated using the array position and the item name?

Thank you for your help!!

Link to comment
Share on other sites

Ha. I saw the thread title, made a guess, and was totally right :D

 

1. mysql_fetch_array will give you two values for every column in the query. One value has a number (an offset 0->6) as a key, one has a string (a column name) as a key. Seven columns in the result means 14 items in the array.

2. You're foreaching on the array when you don't need to. Shouldn't, even. What you want is an array. What you have is an array. You don't have to do anything else.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.