หน้าเว็บ

Wednesday, February 3, 2016

แสดงผลข้อมูลที่ได้จากการ Query ด้วย MySQLi

แสดงผลข้อมูลที่ได้จากการ Query ด้วย MySQLi โดยดึงฟิวด์ต่างๆมาแสดงในตารางให้อัตโนมัติ

<?php
$mysqli = new mysqli($dbconfig['db_server'],$dbconfig['db_username'],$dbconfig['db_password'],$dbconfig['db_name']); 
if ($mysqli->connect_errno) {
 die( "Failed to connect to MySQL Vtiger: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error);
} 
$mysqli->set_charset("utf8");

$query = "SELECT * FROM tbl1 ";

$res = $mysqli->query($query);
?>

<table border=0 cellspacing=1 cellpadding=3 width="100%" class="lvt small">
 <tr>
  <td class="lvtCol">#</td>
 <?php while ($f = $res->fetch_field()) { ?>
  <td class="lvtCol"><strong><?php echo $f->table.".".$f->name; ?></strong></td>
 <?php } ?>
 </tr>
<?php $c=0; while($row = $res->fetch_array(MYSQLI_NUM)){ $c++; ?>
 <tr bgcolor=white onMouseOver="this.className='lvtColDataHover'" onMouseOut="this.className='lvtColData'">
  <td><?php echo $c; ?></td>
  <?php for($i=0; $i < $res->field_count; $i++){ ?>
  <td <?php if(is_numeric($row[$i])){ ?> style="text-align:right;" <?php } ?> nowrap="nowrap">
  <?php 
  echo is_numeric($row[$i]) ? number_format($row[$i]) : $row[$i]; 
  if(is_numeric($row[$i])){
   $sum[$i] = !isset($sum[$i]) ? $row[$i] : $sum[$i]+$row[$i];
  }
  ?>
  </td>
  <?php } ?>
 </tr>

<?php } ?>
 <tr>
 <td></td>
<?php for($i=0; $i < $res->field_count; $i++){ ?>
 <td style=" text-align:right;"><?php if(isset($sum[$i])){ echo '<strong>'.number_format($sum[$i]).'</strong>'; } ?></td>
<?php } ?>
</tr>

</table>

No comments:

Post a Comment