0

I tried to print the Mysql fetched rows into html table using php. However, when using the following code, the first fetched row is repeatedly printing. It looks like the $row hold the first fetched value. I found a similar problem here. But I would like to know about working with the for loop. Thanks

for ($j=0;$j<=$len2;$j++)
 {       

 $sql = "SELECT * FROM database_search WHERE gene_id LIKE'%$key%'";    

 $qry = $dbo->prepare($sql);
 $qry->execute();
 $row = $qry->fetch(PDO::FETCH_ASSOC);     
 $val = array_values($row);



echo "<tr>";
for ($k=0;$k<=4;$k++)
    { 
           $x=$val[$k];         
      echo "<td style=font-size:7.9px>$x</td>"; 

    }
echo "</tr>";

}

2
  • what does the variable $len2 doing? Inside the loop like condition $key is same, then wats the use of the loop? have you tried foreach($val as $res) {..} Commented Mar 18, 2015 at 4:56
  • This is possible that $row only have one record fetching from database and than your for ($k=0;$k<=4;$k++) loop print that only one record 5 time because you are using print under this loop, this loop will run 5 time. Commented Mar 18, 2015 at 5:02

3 Answers 3

0
<table>
<?php
  while($row = $qry->fetch(PDO::FETCH_ASSOC)){
     echo '<tr>';
       foreach($row as $cell){ echo '<td>'.$cell.'</td>'; }
     echo '</tr>';
  } 
?>
</table>
Sign up to request clarification or add additional context in comments.

Comments

0

After fetching the query as $row variable, you need to use the following code instead

foreach($row as $tr) {
    echo "<tr>";
    echo "<td style=font-size:7.9px>".$tr['col1']."</td>";  
    echo "<td style=font-size:7.9px>".$tr['col2']."</td>";  
    echo "</tr>";             
} 

Comments

0

This is possible that $row only have one record fetching from database and than your for ($k=0;$k<=4;$k++) loop print that only one record 5 time because you are using print under this loop, this loop will run 5 time.

Try the following code.

foreach($row as $val) {
    echo "<tr>";
    echo "<td style=font-size:7.9px>".$val['column Name']."</td>";  
    echo "</tr>";             
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.