Olaf K.
Olaf K.

Reputation: 39

how to get the mysql columns names including the right result values in one loop

I ask in connection to this article: How to get the columns names along with resultset in php/mysql?

$selecttable = mysql_query("SELECT * FROM $tablename WHERE (preis_bis <= '$price_upper' AND preis_bis > '$price_lower') LIMIT 1");
for ($i = 0; $i < mysql_num_fields($selecttable); $i++) {
  $field_info = mysql_fetch_field($selecttable, $i);

  // not WORKING
  while($rowvalue = mysql_fetch_row($selecttable)) {
    echo "<tr><td>Price: ".$rowvalue[$i]."</td></tr>";
  }

  echo "<tr><td style='border:1px solid #c0c0c0;padding:10px;'><!-- {$field_info->name} -->";
  // get Logo and provider name
  $select_getlogo = mysql_query("SELECT * FROM rrv_anbieter WHERE aid = '$field_info->name' LIMIT 1");
  while($row_logo = mysql_fetch_object($select_getlogo)){
    echo $row_logo->name.'<br><img src="images/'.$row_logo->logo.'" style="max-width: 200px;">';
  }      
  #while($rowvalues2 = mysql_fetch_row($selecttable)) {        
  #  foreach($rowvalues2 as $_column) {
  #    echo "<td>{$_column}</td>";
  #  }      
  #}      
  echo "</td></tr>";       
}

I do not get it to get the correct row value within the "for" loop. Writing col names is working, but showing additionally the right value in same loop not.

Can someone help?

Upvotes: 1

Views: 171

Answers (1)

Fevly Pallar
Fevly Pallar

Reputation: 3099

You need to iterate once more in the inner loop to get all rows of the table's columns.

while($rowvalue = mysql_fetch_row($selecttable)) {       
        foreach($rowvalue as $r){
        echo "<tr><td> ".$r."</td></tr>";
        }
  }

$rowvalue[$i] showed rows incorrectly because it's following index based on the outer loop which is $i. So basically the loop will print all rows of each column for n-times where n=number of all columns, not just the price column. .

And you can also print all elements per-$rowvalue at once with :

while($rowvalue = mysql_fetch_row($selecttable)) {       
            $allElements = implode(",",$rowvalue ); // comma ',' is the separator
            echo "<tr><td>". $allElements."</td></tr>";
            }
      }

Upvotes: 1

Related Questions