-1

i have a database in which 2 records are present in each record i have 5 column name as "col1" "col2" "col3" "col4" "col5"

i'm using CodeIgniter i'm passing the database data from controller to view result["row2"] as an array and in view i want to print it in a table but i get an error like that

Message: Undefined property: stdClass::$col

  for ($i = 0; $i < count($row2); $i++) {
     echo '<tr>';
     for ($j = 1; $j <= 5; $j++) {
     echo "<td>".$row2[$i]->col.$j."</td>";
  } 
echo '</tr>';
}

compiler does not combine the col and loop value which is 1,2,3,4,5

B. Desai
  • 16,414
  • 5
  • 26
  • 47
dani
  • 43
  • 6
  • Post your complete code – itsme Mar 31 '18 at 10:09
  • Here you're not accessing $obj->colN but concatenating the value of $obj->col with the value of N though. Look into "[getting PHP object property by string](https://stackoverflow.com/questions/804850/get-php-class-property-by-string)" – ppajer Mar 31 '18 at 10:10

1 Answers1

3

First store your concatenation in one variable then use that variable to get data

for ($j = 1; $j <= 5; $j++) {
     $col_name = "col".$j
     echo "<td>".$row2[$i]->$col_name."</td>";
  } 

And if you are getting result in array(not in object) then change echo line as below

echo "<td>".$row2[$i][$col_name]."</td>";
B. Desai
  • 16,414
  • 5
  • 26
  • 47