-1

Background: I am reviewing a friends project and I am trying to save him some time by using for loops wherever possible in his project. See below an example of what is currently happening (keep in mind there are actually 105 headers I am only using 9 in my example.)

My Thoughts: Instead of looping through the returned DB data and assigning those values to variables just to use those same variables in a table directly below it... I want to use the DB array values in the table directly. Also since the inputs in each increment there names I should be able to do all of this in a loop.

CURRENT LONG FORM CODE:

 while($rows = mysqli_fetch_assoc($pl_bud)){    
            $header_0       = $rows['col_tot_0'];
            $header_1       = $rows['col_tot_1'];
            $header_2       = $rows['col_tot_2'];
            $header_3       = $rows['col_tot_3'];
            $header_4       = $rows['col_tot_4'];
            $header_5       = $rows['col_tot_5'];
            $header_6       = $rows['col_tot_6'];
            $header_7       = $rows['col_tot_7'];
            $header_8       = $rows['col_tot_8'];
            $header_9       = $rows['col_tot_9'];

    echo "<tr>

                    <td><input type='text' name='header_0' value='$header_0'/></td>
                    <td><input type='text' name='header_1' value='$header_1'/></td>
                    <td><input type='text' name='header_2' value='$header_2'/></td>
                    <td><input type='text' name='header_3' value='$header_3'/></td>
                    <td><input type='text' name='header_4' value='$header_4'/></td>
                    <td><input type='text' name='header_5' value='$header_5'/></td>
                    <td><input type='text' name='header_6' value='$header_6'/></td>
                    <td><input type='text' name='header_7' value='$header_7'/></td>
                    <td><input type='text' name='header_8' value='$header_8'/></td>
                    <td><input type='text' name='header_9' value='$header_9'/></td>
                    </tr>";

        }

THIS IS WHAT I AM TRYING TO ACCOMPLISH

 while($rows = mysqli_fetch_assoc($pl_bud)){  

echo "<tr>";
for($i = 0; $i <= 9; $i++){
<td><input type='text' name='header_". $i ."' value='". $rows['col_tot_$i']  ."'/></td>";
}
echo "</tr>";
 }

My Question: But I am not sure how to correctly increment the $rows['col_tot_#']

Denoteone
  • 4,043
  • 21
  • 96
  • 150
  • Helpful reads: https://stackoverflow.com/a/41199224/2943403 and https://stackoverflow.com/a/39144966/2943403 just declare and use the `$key`. – mickmackusa Apr 25 '19 at 01:03

1 Answers1

2

$rows['col_tot_$i'] is just being interpreted as a string literal. Do this instead: $rows['col_tot_'.$i]

Crayons
  • 1,906
  • 1
  • 14
  • 35