ali ali - 4 months ago 13
MySQL Question

pass array value to colspan to create column table in php

I am having a problem to pass a value from array to colspan, so I can have dynamic multi column.

$my_values = array();
while ($data=mysqli_fetch_assoc($result)) {
foreach ($data as $key => $value) {
$my_values[] = $value;
}
}
print_r($my_values);


and this is the output the I got for printing the $my_values:

Array ( [0] => 3 [1] => 2 [2] => 1 )

What I am trying to do here is creating table and pass those array to colspan:

$query = "SELECT * FROM assignments WHERE course_id=1";
$result1 = mysqli_query($conn, $query);
if (mysqli_num_rows($result1) != 0) {
while ($row=mysqli_fetch_assoc($result1)) {
echo '<th colspan="'.$my_values['0'].'">'.$row['assignment_name'].'</th>';
}
}


where is $my_values['0'] will get just 3. what I am trying to do here is I want to get index 0 first, then index 2 then index 3. so the first one can create 3 columns and the second one 2 columns and the third 1 columns.

can you help me guys with this issue.

Answer

Use below code. it may help you with

$query = "SELECT * FROM assignments WHERE course_id=1";
        $result1 = mysqli_query($conn, $query);
        if (mysqli_num_rows($result1) != 0) {
            $i = 0; //-------------->INITIALIZE THE VARIABLE
        while ($row=mysqli_fetch_assoc($result1)) {
          echo '<th colspan="'.$my_values[$i].'">'.$row['assignment_name'].'</th>';
          $i++; //----------------> INCREMENT THE VARIABLE
        }
      }
Comments