0

I have a Product master in which I have 2 fields, ONE is for Main Product (Field name 'Under') and SECOND is for Sub-product (Field name is 'Prod_desc) What I want is a nested loop where I capture all codes (field name is Cylno) from transaction Table (ECR_CBDC).

I have 2 nested loops, First while loop is for PRODUCT_MASTER where based on user selection of a Main-product the sub-products are selected and SECOND loop is for collecting the codes for all sub-products.

Now the issue is it collects only 1 value as the FOR loop overwrites the previous value. Is there any other loop which can hold the previous value of each sub-product.

$p=mysql_query("SELECT * FROM PRODMAST WHERE Under='$product'");
while ($p2=mysql_fetch_assoc($p))
{
    $prodesc=$p2['Prod_desc'];

    $dc=mysql_query("SELECT * FROM ECR_CBDC WHERE Prod_desc='$prodesc'  AND usr='$user'");
    $num_rows = mysql_num_rows($dc);
    $fill_from_array = array(); /* as "value"=>"option" */
    for($i = 1; $i <= $num_rows; $i++)
    {
        $row = mysql_fetch_assoc($dc);
        $fill_from_array[$row['Cylno']] = $row['Cylno'];
    }
}

2 Answers 2

1

If I understand what you're asking - $fill_from_array only collects one row's worth - I think you need to define $fill_from_array outside of the first loop, so...

$p=mysql_query("SELECT * FROM PRODMAST WHERE Under='$product'");
$fill_from_array = array(); /* as "value"=>"option" */
while ($p2=mysql_fetch_assoc($p))
{
    $prodesc=$p2['Prod_desc'];

    $dc=mysql_query("SELECT * FROM ECR_CBDC WHERE Prod_desc='$prodesc'  AND usr='$user'");
    $num_rows = mysql_num_rows($dc);
    for($i = 1; $i <= $num_rows; $i++)
    {
        $row = mysql_fetch_assoc($dc);
        $fill_from_array[$row['Cylno']] = $row['Cylno'];
    }
}

That way it's not over-writing $fill_from_array each time the while() loop loops. Is that what you mean?

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of emulating a join in code, use the JOIN syntax instead to reduce the number of loops and data transfer:

SELECT * FROM PRODMAST 
INNER JOIN ECR_CBDC ON PRODMAST.Prod_desc=ECR_CBDC.Prod_desc AND usr='$user'
WHERE Under='$product'

2 Comments

@user1387008 As your data set grows, this solution will become much faster than having two loops; just something to keep in mind.
@user1387008 Since you're new to SO ... if the answer is useful you should upvote it (you have enough rep for it now).

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.