PHP MYSQL Associate array and table - php

Here is a code.
This loads all the header part (i.e the header for the table) dynamically from the database.
The below code works fine. But the column is mismatched.
i.e. the first row first column of the header is blank and there is a dislocation in the table.
Code
<table border="1">
<?php
$book_query = mysql_query("select * from book_master");
$i = 0;
while($row = mysql_fetch_assoc($book_query))
{
$columns = array_keys($row);
?>
<th>
<?php
foreach($columns as $column)
{
?>
<td><?php echo $column; ?> </td>
</th>
<?php
}
?>
<tr>
<?php
foreach($row as $key=>$value)
{
?>
<td><?php echo $value; ?></td>
<?php
}
?>
</tr>
<?php
$i++;
}
?>
</table>
EDIT:
Here is my print_r($columns) value:
Array ( [0] => Author Name [1] => Book Name [2] => Rating [3] => Location )
I know the problem is with the loop. Could someone help me out?

You can try to change
<th>
<?php
foreach($columns as $column)
{ ?>
<td><?php echo $column; ?> </td>
<?php
}
?>
</th>
to
<tr>
<?php
foreach($columns as $column)
{ ?>
<th><?php echo $column; ?> </th>
<?php
}
?>
</tr>

Just remove TH tag because its create one extra cell, so your layout messed up
<table border="1">
<?php
$book_query = mysql_query("select * from book_master");
$i = 0;
while($row = mysql_fetch_assoc($book_query))
{
if($i == 0){
$columns = array_keys($row);
?>
<?php
foreach($columns as $column){ ?>
<td><?php echo $column; ?> </td>
<?php } ?>
<?php } ?>
<tr>
<?php
foreach($row as $key=>$value){ ?>
<td><?php echo $value; ?></td>
<?php } ?>
</tr>
<?php
$i++;
}
?>
</table>

Hope this will help someone.
Just I have replaced the TH tag with TR and the output is perfect.
<table border="1">
<?php
$book_query = mysql_query("select * from book_master");
while($row = mysql_fetch_assoc($book_query))
{
$columns = array_keys($row);
?>
<tr>
<?php
foreach($columns as $column){ ?>
<td><?php echo $column; ?> </td>
<?php } ?>
</tr>
<tr>
<?php
foreach($row as $key=>$value){ ?>
<td><?php echo $value; ?></td>
<?php } ?>
</tr>
</table>

Related

How to fetch data in table group by other column in PHP

I have a record like this in database:
section_id description level_id
1 Amethyst 1
2 Betelguise 1
3 Daisy 2
4 Rose 2
I want it to display in my php table just like this:
Level 1
Amethyst
Betelguise
Level 2
Daisy
Rose
Can anyone please help me? I am new at this.
Here's my code:
<table>
<thead>
<tr>
<th>Descriptions</th>
<th>Level</th>
</tr>
</thead>
<?php $sql = "SELECT * FROM tbl_sectiontaken"; ?>
<?php $result = $db->query($sql); ?>
<?php if ($result->num_rows > 0) { ?>
<?php while($row = $result->fetch_assoc()) { ?>
<?php $id = $row['section_id'];
$desc = $row['description'];
$gr = $row['level_id']; ?>
<tbody>
<tr>
<td style="text-transform:capitalized;">
<?php echo $desc; ?>
</td>
<td style="text-transform:capitalized;">
<?php echo $gr; ?>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
But it gives me this result in table:
Descriptions Level
Amethyst 1
Betelguise 1
Daisy 2
Rose 2
You can use group_concat function for this. Use below code if suits your requirements
<?php $sql = "SELECT level_id,GROUP_CONCAT(description) AS description FROM series group by level_id"; ?>
<?php $result = $db->query($sql); ?>
<?php if ($result->num_rows > 0) { ?>
<?php while ($row = $result->fetch_assoc()) { ?>
<?php
$id = $row['section_id'];
$desc = $row['description'];
$gr = $row['level_id'];
$leveArr[$gr][] = $desc;// Create an array with level and description
} } ?>
</tbody>
<table>
<tr><!-- header-->
<?php foreach ($leveArr as $key => $value) { ?>
<td><?php echo "LEVEL " . $key ?></td>
<?php } ?>
</tr>
<tr>
<?php foreach ($leveArr as $key => $value) {
foreach ($value as $key_1 => $data) { ?>
<td><?php
$data = explode(",", $data);
foreach ($data as $key_2 => $final) {
echo $final . "<br>";
}
?></td>
<?php }
} ?>
</tr>
</table>
Updated
Check the sandbox example
Change query with GROUP_CONCAT
SELECT GROUP_CONCAT(if (description ='', null, description)) as description,count(description) as heigher,level_id FROM yourtablename WHERE 1 GROUP BY level_id
And After.They return array like this
$arr=[['description'=>'a,b,c,d','level_id'=>'1','heigher'=>'4'],['description'=>'a,b,c,d','level_id'=>'2','heigher'=>'4']]; ?>
Then Finally Create Table as like this
$sql="SELECT GROUP_CONCAT(if (description ='', null, description)) as description,count(description) as heigher,level_id FROM yourtablename WHERE 1 GROUP BY level_id";
$result = $conn->query($sql);
$arr =[];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$arr[]=$row;
}
}
<table>
<thead>
<tr>
<?php foreach ($arr as $key => $value): ?>
<th><?='level'.$value['level_id']?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php
$arr = array_filter($arr,function($a=[]){
return $a['level_id'] != 0
}) //filter level not a zero
$h = max(array_map(function($a=[]){
return $a['heigher']; //filter array['heigher only']
},$arr)); // its get the heighest length of description value like [10,15,100]=>100
foreach ($arr as $key => $value){
$value['description'] = !empty($value['description']) ?explode(',',$value['description']):'';
$arr[$key]=$value;
}
?>
<?php for ($i=0; $i < $h[0]; $i++) {?>
<tr>
<?php foreach ($arr as $key => $value): ?>
<th><?=isset($value['description'][$i])? $value['description'][$i] :''?></th>
<?php endforeach; ?>
</tr>
<?php }?>
</tbody>
</table>

Codeigniter multiple foreach loop

I have two tables meals type and meals. I want to print each meals corresponding to its meals type.
Error is that only showing last meals type meals only
view page is like
View
<?php
foreach ($mealstype as $type) {
?>
<h2><?php echo $type->type; ?></h2>
<table class="table table-bordered">
<tr>
<th>Meals</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
foreach ($meals as $meals_get) {
?>
<tr>
<td><?php echo $meals_get->item; ?></td>
<td><?php echo $meals_get->price; ?></td>
</tr>
<?php } ?>
<tr>
<td> <input type="checkbox" class="ck" value="total"> Toal</td>
<td>2050</td>
</tr>
</tbody>
</table>
<?php
}
?>
Controller
function availability() {
$this->data['mealstype'] = $this->Home_model->mealstype();
foreach ($this->data['mealstype'] as $type) {
$typeid = $type->id;
$meals[] = $this->Home_model->meals($typeid, $hotel_id);
}
$this->data['meals'] = $meals[];
$this->load->view('home2', $this->data);
}
Please check this answer
Controller:
public function availability() {
$build_array = array();
mealstype= $this->Home_model->mealstype();
foreach($mealstype as $row){
$build_array[] = array(
'parent_array' => $row,
'child_array' =>$this->Home_model->meals($row->id,$hotel_id),
'child_sum' =>$this->Home_model->meals_sum($row->id,$hotel_id)
);
}
$this->data['build_array'] = $build_array;
}
and the view page is like this:
View:
<?php foreach($build_array as $type){?>
<h2><?php echo $type['parent_array']->type;?></h2>
<table class="table table-bordered">
<tr>
<th>Meals</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
foreach ($type["child_array"] as $meals_get) {?>
<tr>
<td><?php echo $meals_get->item;?></td>
<td><?php echo $meals_get->price;?></td>
</tr>
<?php }?>
<tr>
<td> Toal</td>
<td>2050</td>
</tr>
<?php } ?>
Controller, check "hotel_id"
function availability()
{
$this->data['mealstype'] = $this->Home_model->mealstype();
if( count( $this->data['mealstype'] ) > 0 )
{
foreach($this->data['mealstype'] as $type)
{
$type->meals = $this->Home_model->meals( $type->id, $hotel_id ); // hotel_id no declared???
}
}
$this->load->view('home2', $this->data);
}
View
<?php if( count( $mealstype ) > 0): foreach( $mealstype as $type ): ?>
<h2><?php echo $type->type; ?></h2>
<table class="table table-bordered">
<thead>
<tr>
<th>Meals</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php if( count( $type->meals ) > 0 ): foreach( $type->meals as $meals_get ): ?>
<tr>
<td><?php echo $meals_get->item; ?></td>
<td><?php echo $meals_get->price; ?></td>
</tr>
<?php endforeach; endif; ?>
<tr>
<td><input type="checkbox" class="ck" value="total"> Toal</td>
<td>2050</td>
</tr>
</tbody>
</table>
<?php endforeach; endif ?>
Try to replace into this :
function availability() {
$data = array();
$data['mealstype'] = $this->Home_model->mealstype();
foreach ($data['mealstype'] as $type) {
$typeid = $type->id;
$type->meals = $this->Home_model->meals($typeid,$hotel_id);
}
$this->load->view('home2', $data);
}
check it and print_r($data); what it comes set on the basis of that in view file..
You have $hotel_id I am not sure where you set this I can not see it any where else.
We also need to see your model
public function availability() {
$data['mealstypes'] = array();
$mealstypes = $this->home_model->mealstype();
foreach ($mealstypes as $mealstype)
{
$meals = array();
$meals_results = $this->home_model->meals($mealstype->id, $hotel_id);
foreach ($meals_results $meal_result) {
$meals[] = array(
'mealstype' => $meal_result->mealstype,
'price' => $meal_result->price
);
}
$data['mealstypes'][] = array(
'type' => $mealstype->type
'meals' => $meals
);
}
$this->load->view('someview', $data);
}
View
<?php foreach ($mealstypes as $mealstype) {?>
<h2><?php echo $mealstype['type'];?></h2>
<?php foreach ($mealstype['meals'] as $meal) {?>
<?php echo $meal['mealstype'];?>
<?php echo $meal['price'];?>
<?php }?>
<?php }?>

PDO FETCH all return one row in HTML

foreach($ligne as $value){
$result = $bdd->query('SELECT count(d.DNUMERO) as nbr, SUM(d.DINIPPL) as total FROM dossier d, cliregroup c, doinfsup i WHERE i.DSNUMERO = d.DNUMERO AND d.DNUMCLI = c.NUMCLI AND i.INFOSUPPLM REGEXP "([1][4-6][0-9a-zA-Z]{6}[0-9]{4})" AND INFOSUPPLM NOT REGEXP "([0-1][0-4][0-9a-zA-Z]{6}[0-9]{4})" AND i.DSNUMERO LIKE "16%" AND c.CODEREGROUP LIKE "'.$value.'"');
$table = $result->fetchAll();
print_r($table);
}
<?php include_once('header.html'); ?>
My $table return one row not the full table (the last row). In the php file it's good:
<?php print_r($table); ?>
<table class="table">
<?php foreach ($table as $key => $q): ?>
<?php foreach ($secteur as $key => $s): ?>
<tr>
<th><?php echo $key; ?></th>
<td><?php echo $q['nbr']; ?></td>
<td><?php echo $q['total']; ?></td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
</table>
</body>
</html>
You are overwriting $table each time through the loop. Try an array:
$table[] = $result->fetchAll();
Other issues:
<?php foreach ($table as $key => $q): ?>
<?php foreach ($secteur as $key => $s): ?>
You overwrite $key with the second loop.
Where does $secteur come from? It's not defined. Maybe you meant $q?

Table Province District and Subdistrict with PHP

I have table Province District and Subdistrict in my database and i want to print as output in html table as below:
but i get this:
here are my code:
<?php
$orderProv = 1;
//$QueryProvinces = Query Province;
foreach ($QueryProvinces as $QueryProvince) {
?>
<tr>
<td> <?php echo $orderProv; ?></td>
<td> <?php echo $QueryProvince->nameProv; ?></td>
<?php
//$QueryDistricts = Query District;
foreach ($QueryDistricts as $QueryDistrict ) {
?>
<td> <?php echo $QueryDistrict ->nameDist; ?></td>
<?php
}
?>
</tr>
<?php
}
?>
Please help me,
Thanks a lot.
You need to close and then open a new row with each loop of foreach ($QueryDistricts as $QueryDistrict ). Try something like this -
<?php
$orderProv = 1;
//$QueryProvinces = Query Province;
foreach ($QueryProvinces as $QueryProvince) {
?>
<tr>
<td> <?php echo $orderProv; ?></td>
<td> <?php echo $QueryProvince->nameProv; ?></td>
<?php
//$QueryDistricts = Query District;
$i = 0; // simple counter
foreach ($QueryDistricts as $QueryDistrict ) {
if($i>0){ // if not the 1st row, echo new row start
?>
<tr>
<td> </td>
<td> </td>
<?php
}
?>
<td> <?php echo $QueryDistrict ->nameDist; ?></td>
</tr>
<?php
$i++;
}
}
?>
Table Result:
html source code:
Complete code:
<table id="example1" class="table table-bordered table-condensed table-hover">
<thead>
<tr>
<th>No.</th>
<th width="20%">Provinsi</th>
<th>Kabupaten/Kotamadya</th>
<th>Kecamatan</th>
<th>Pendamping</th>
<th>Telepon</th>
<th>Email</th>
<th>Status Laporan</th>
</tr>
</thead>
<tbody>
<?php
$thecolor = array ("olive", "navy", "aqua", "maroon", "green", "yellow", "orange", "purple", "light-blue", "red");
//$infLokasis = Query;
$nomorProv = 1;
$thecolorProv = $thecolor;
$colorProv = 0;
foreach ($infLokasis as $infLokasi) {
# code... cetak nama provinsi
if ($colorProv >= 10) {
# code... warna set
$colorProv = 0;
}
?>
<tr>
<td><strong class="text-<?php echo $thecolorProv[$colorProv];?> small"><?php echo $nomorProv.". ";?></strong></td>
<td><strong class="text-<?php echo $thecolorProv[$colorProv];?> small"><?php echo $infLokasi->lokasi_nama;?></strong></td>
<?php
$i = 0; // simple counter
//$infKabkotas = Query;
$nomorKabkota = 1;
$thecolorKabkota = $thecolor;
$colorKabkota = 0;
foreach ($infKabkotas as $infKabkota) {
# code... cetak nama kabupaten
if ($colorKabkota >= 10) {
# code... warna set
$colorKabkota = 0;
}
if($i>0){ // if not the 1st row, echo new row start
?>
<tr>
<td></td>
<td></td>
<?php
}
?>
<td><strong class="text-<?php echo $thecolorKabkota[$colorKabkota];?> small"><?php echo $nomorProv.".".$nomorKabkota.". ".$infKabkota->lokasi_nama; ?></span></td>
<?php
$j = 0;
$infKecamatans = Query;
$nomorKecamatan = 1;
$thecolorKecamatan = $thecolor;
$colorKecamatan = 0;
foreach ($infKecamatans as $infKecamatan) {
if ($colorKecamatan >= 10) {
# code... warna set
$colorKecamatan = 0;
}
if($j>0){ // if not the 1st row, echo new row start
?>
<tr>
<td></td>
<td></td>
<td></td>
<?php
}
?>
<td><strong class="text-<?php echo $thecolorKecamatan[$colorKecamatan];?> small"><?php echo $nomorProv.".".$nomorKabkota.". ".$nomorKecamatan.". ".$infKecamatan->lokasi_nama; ?></strong></td>
<?php
$k = 0;
$idDaerah = substr($infKecamatan->lokasi_kode, 0,10);
$infPendampings = $db->get_results("SELECT id_p, nama_p, telepon_p, email_p FROM pendamping WHERE id_d LIKE '$idDaerah%' ");
$nomorPendamping = 1;
$thecolorPendamping = $thecolor;
$colorPendamping = 0;
if ($infPendampings) {
foreach ($infPendampings as $infPendamping) {
if($k>0){ // if not the 1st row, echo new row start
?>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<?php
}
?>
<td>
<?php echo "<span class=\"text-".$thecolorPendamping[$colorPendamping]." small\">".$nomorPendamping.". "; ?></span>
<?php echo "<a href=\"vpendamping.php?str=".encryptor('encrypt', $infPendamping->id_p)."\" class=\"text-".$thecolorPendamping[$colorPendamping]." small\" target=\"_blank\">".namaGelar($infPendamping->nama_p); ?>
</td>
<td class="small"><?php echo $infPendamping->telepon_p; ?></td>
<td class="small"><?php echo $infPendamping->email_p; ?></td>
<td class="small"><?php echo "<i class=\"fa fa-fw fa-square-o text-red\"></i> Kosong"; ?></td>
<?php
$nomorPendamping++;
$colorPendamping++;
$k++;
}
}
else {
# code... row kosong
#if i romove 4 line code below... Provinsi name and Kabupaten/Kotamadya name should appear
echo "<td></td>\n";
echo "<td></td>\n";
echo "<td></td>\n";
echo "<td></td>\n";
}
?>
</tr>
<?php
$nomorKecamatan++;
$colorKecamatan++;
$j++;
}
?>
<?php
$i++;
$colorKabkota++;
$nomorKabkota++;
} // End infKabkota
$nomorProv++;
$colorProv++;
}
?>
</tbody>
</table>

php code to break page after 6th row

I try to display 2 table side by side with php code....
but i need to display only 6 table on single page ......and rest on another page......
so plz can any one help me to break page or break loop after 6th iteration..... 7th table display on another page like wise...
plz see my image attached below....i am facing problem on print preview...
page breaks my table during print...like below image...
I attached croped imaged here...
my page actuaally display 8 tables on single page...but i need is only 6 on one page.
below is my code..
<?php if (is_array($data)) { foreach($data as $row) { ?>
<table border="1px solid #666" summary="" width="48%" class="pos_fixed1">
<thead>
<tr>
<td colspan="4">Dainik Bhaskar Nagpur</td>
</tr>
<tr>
<td>Receipt</td>
<td><?php echo htmlspecialchars($row['receipt_no']); ?></td>
<td>Coupon</td>
<td><?php echo htmlspecialchars($row['coupon']); ?></td>
</tr>
<tr>
<td>Receipt Date</td>
<td><?php echo htmlspecialchars($row['bookingdate']); ?></td>
<td>Coupon Date</td>
<td><?php echo htmlspecialchars($row['coupondate']); ?></td>
</tr>
<tr>
<td>Copy Start Date</td>
<td><?php echo htmlspecialchars($row['startingdate']); ?></td>
<td>HawkerName</td>
<td><?php echo htmlspecialchars($row['hawkername']); ?></td>
</tr>
<tr>
<td>SubagentName</td>
<td><?php echo htmlspecialchars($row['subagentname']); ?></td>
<td>CenterName</td>
<td><?php echo htmlspecialchars($row['ward']); ?></td>
</tr>
<tr>
<td>customer</td>
<td><?php echo htmlspecialchars($row['customer_name']); ?></td>
<td>Address</td>
<td><?php echo htmlspecialchars($row['society']); ?></td>
</tr>
</thead>
</table>
<?php } }?>
Try using CSS:
<style>
#media print {
.pageBreak {
page-break-after: always;
}
}
</style>
And at every 6 table, add a pageBreak:
<?php
$lineCounter = 0;
if (is_array($data)) {
foreach($data as $row) {
$lineCounter++;
?>
<!-- output a table... -->
<?php
if($lineCounter % 6 == 0) {
echo '<span class="pageBreak"></span>' . PHP_EOL;
}
}
}
?>
<?php
// get total records
TotalNoOfRecords = count($data);
$Count = 1;
foreach($data as $row) {
// write here your content
// break page after 6 rows
if($Count % 6 == 0 && $Count != $TotalNoOfRecords)
{
echo "<p style='page-break-after:always'></p>";
}
$Count++;
}
?>
try this is code or visit link
<?php
$q = "SELECT * FROM your_table ";
$myq = mysqli_query($link, $q);
$fixtures ='';
$i=0;
while($row=mysqli_fetch_assoc($myq)) {
$r[]=$row;
}
foreach ($r as $val) {
$i++;
?>
<!-- your value from database -->
<table>
<tr>
<td><?php echo $val['your_column']; ?></td>
</tr>
</table>
<!-- your value from database -->
<?php
if($i % 6==0){
echo '<div style="page-break-after: always;">[------ break ------]</div>' . PHP_EOL;
$i=0;
}
}
?>

Categories