Wednesday 5 September 2018

php while and loops to fill array does not work

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'];
    }
}


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?

0 comments:

Post a Comment