Thursday 15 October 2015

Foreach statement with MySQL select query in PHP


Foreach statement with MySQL select query in PHP

Here i have given a example for better understand...
<?php

class myclass{

public function fetchCat(){
   
    $sql = "select c.cat_id,cat_name,product_name,price from categories as c left join products as p on p.cat_id=c.cat_id";
$result = $this->query($sql);
$Finarray = array();
while($rows = mysql_fetch_assoc($result)){
$Finarray[] = $rows;
}
return $Finarray;

    }

}

$cat = $obj->fetchCat();

?>

<table border="1">
    <tr>
        <td>Category Id</td>
        <td>Product Name</td>
        <td>Product Price</td>
        <td>Category Name</td>
    </tr>
    <?php foreach($cat as $_cat): ?>
        <tr>
            <td><?php echo $_cat['cat_id']; ?></td>
            <td><?php echo $_cat['product_name']; ?></td>
            <td>
<?php if(!$_cat['price']): ?>
                &nbsp;
                <?php else: ?>  
<?php echo $_cat['price']; ?>
                <?php endif; ?>  
            </td>
            <td><?php echo $_cat['cat_name']; ?></td>
        </tr>  
    <?php endforeach; ?>
</table>

No comments: