php loop from database - php

i have a code that store data in database as an object with serialize(),
and show this on table in loop from database each category have 'payment' column that has the array with the payments data (example:[num,string,date]) And there could be several payment to each category,
but the issue is that now it show all payments category in the table one under the other
i try to do it nicer so that In the column that displays the the payments will be a
modal button that displays the payments of each category in the modal but it display the first value on the array to all categories
i try someting to give an id But that's impossible because it prints the information in a loop
that's my code:
function showTable($table, $data, &$totalSum = 0)
{
$totalEestimatedCost = 0;
$totalMyBudget = 0;
if (is_array($data)) {
$tableToShow = '';
$outputData = '<table class="table table-striped table-hover table-responsive-xs table-responsive-sm table-responsive-md table-responsive-lg" >';
$outputData .= "
<thead>
<tr>
<th scope='col'>קטגוריה</th>
<th scope='col'>התקציב שלי</th>
<th scope='col'>עלות בפועל</th>
<th scope='col'>תשלומים</th>
<th scope='col'>יתרה לתשלום</th>
<th scope='col'>הקובץ</th>
</tr>
</thead>
<tbody>
";
$totalHefresh = 0;
for ($i = 1; $i < count($data) / 2; $i++) {
$arrData = unserialize($data[$i]);
$heb_name = $arrData['data']['field_name_heb'];
$files = $arrData['data']['files'];
$myBudget = isset($arrData['data']['my_budget'])?$arrData['data']['my_budget']:0;
$myBudgetNumber = number_format($myBudget);
$estimatedCost = isset($arrData['data']['estimated_cost'])?$arrData['data']['estimated_cost']:0;
$estimatedCostNumber = number_format($estimatedCost);
$filesData = returnFiles($files, $arrData['data']['field_name'], $arrData['data']['stage']);
$total_field_cost = isset($arrData['data']['total_cost'])?$arrData['data']['total_cost']:0;
$payments = returnPayments($arrData['payments'], $arrData['data']['field_name'], $arrData['data']['stage']);
$hefresh = $estimatedCost - $total_field_cost;
$hefreshNumber = number_format($hefresh);
$totalEestimatedCost += $arrData['data']['estimated_cost'];
$totalEestimatedCostNumber = number_format($totalEestimatedCost);
$totalMyBudget += $arrData['data']['my_budget'];
$totalMyBudgetNumber = number_format($totalMyBudget);
$totalHefresh += $hefresh;
$totalHefreshNumber = number_format($totalHefresh);
$outputData .=
"<tr>
<td>$heb_name</td>
<td class='text-center'> <span> ₪ </span> <span>$myBudgetNumber</span> </td>
<td class='text-center'> <span> ₪ </span> <span>$estimatedCostNumber</span> </td>
<td >$payments</td>
<td class='text-center'><span> ₪ </span> <span>$hefreshNumber</span></td>
<td style='height: 118px'>$filesData</td>
</tr>
</tbody> ";
//echo "<pre>";
//print_r($arrData);
}
printDinamicDataTable($table , $outputData , $totalEestimatedCost , $totalHefresh);
$outputData .= "</table>";
$outputData .= "<div class='total-hfresh'>
<div>סה\"כ התקציב שלי: $totalMyBudgetNumber</div>
<div>סה\"כ עלות בפועל: $totalEestimatedCostNumber</div>
<div>יתרה לתשלום: $totalHefreshNumber</div>
</div>";
//echo "<br> $outputData";
$totalSum += $totalHefresh;
return $outputData;
}
};
function returnPayments($payments, $field, $stage)
{
$dataToReturn = '';
foreach ($payments as $key => $value) {
$payment = $value['payment'];
$date = $value['date'];
$note = $value['note'];
$dataToReturn .= "<table style='width: 100%;margin-bottom: 5px'><tr><td
class='pay-td1'>₪ $payment </td>";
$dataToReturn .= " <td class='pay-td2'>$note </td>";
$dataToReturn .= "<td class='pay-td3'> $date </td>";
$dataToReturn .= "<td><button data-stage='$stage' data-id='$key' data-
name='$field' class='deletePayment btn btn-danger'><b>X</b>
</button></td></tr></table>";
}
return $dataToReturn;
}

Related

Getting contents of dropdown from table and storing it in an array

I just want to get the contents of the dropdown and store it in array.
I am able to display the dropdown but it doesn't get the contents of what I selected.
echo '<br><br><br><br><br>
<div class="Table">
<table border="2pt solid black" align="left" cellpadding="2px" bordercolor=black>
<tr>
<td width = "7%">
<div align = "left"><b>BRAND NAME</div></b>
</td>
<td width = "7%">
<div align = "left"><b>INGREDIENT</div></b>
</td>
<td width = "3%">
<div align = "left"><b>QUANTITY</div></b>
</td>
<td width = "7%">
<div align = "left"><b>MEASUREMENT</div></b>
</td>
</tr>';
for ($x = 0; $x < sizeof($rowarray); $x++) {
$query = "select R.name AS RAWNAME, I.name AS INGREDIENTNAME, R.quantity AS RAWQUANTITY from rawmaterial R JOIN ingredient I ON R.ingredient_id = I.ingredient_id where R.rawmaterial_id='{$rowarray[$x]}'";
$res = mysqli_query($dbc, $query);
while ($fetch = mysqli_fetch_array($res, MYSQL_ASSOC)) {
echo "<tr>
<td width=\"7%\">
<div align=\"left\">{$fetch['RAWNAME']}</div>
</td>
<td width=\"3%\">
<div align=\"left\">{$fetch['INGREDIENTNAME']}</div>
</td>
<td width=\"3%\">
<div align=\"left\"><input type='name' name='quantity[]' placeholder={$fetch['RAWQUANTITY']}></input></div>
</td>
<td width=\"7%\">
<div align=\"left\">";
echo "<select name = 'measure'>";
$mesr = mysqli_query($dbc, 'select measure from measure_ref');
while ($row = mysqli_fetch_array($mesr, MYSQLI_ASSOC)) {
$mes = $row['measure'];
echo '<option value ='.$mes.'>'.$mes.'</option>';
}
echo "</select>";
echo "</div>";
echo "</td>";
echo "</tr>";
}
}
echo '</table></div>';
$messarray = array();
$mes = $_POST['measure'];
$row = array();
foreach ($mes as $row) {
array_push($messarray, $row);
}
Check below points.
Make sure your dropdown is within form
As you are creating multiple dropdown you should give name with '[]'(measure[]),like you have given to 'quantity[]'.

Get all data for parent and child rows

I want to retrieve all mysql table data using this script:
<?php
//WHERE id_post = '$id_post'
$sq = mysql_query("SELECT * FROM article_comments ") or die(mysql_error());;
connect();
while($row = mysql_fetch_assoc($sq)){
$result[$row["parent_id"]][] = $row["id"];
}
$rowIsOpened = false; //Indicates whether a row is currently opened.
//I'm using $rowIsOpened because the row immediately after the rowspanned cell shouldn't be closed.
echo <<<HTML
<table style="border-color: black;border-style: solid;">
<thead>
<tr>
<th>Parent</th>
<th>Children</th>
</tr>
</thead>
<tbody>
HTML;
//Echo a bunch of HTML before actually looping
foreach ($result as $parent => $children) {
echo "<tr style='border-color: black;border-style: solid;vertical-align:top;'>";
echo "<td rowspan=";
echo count($children); //Span over <how many children are> rows
echo " style='border-color: black;border-style: solid;' >$parent</td>";
$rowIsOpened = true; //Row is opened
foreach ($children as $child) {
if (!$rowIsOpened) {
echo "<tr>";
} //Only open a row if row is not opened
echo "<td style='border-color: black;border-style: solid;'>$child</td>";
echo "</tr>";
$rowIsOpened = false; //Row is now closed. Ready for next iteration.
}
}
//Close the table tags etc.
echo <<<HTML
</tbody>
</table>
HTML;
?>
This script creates an output table like that
Parent Children
0 1
3
4
5
1 1
2
My problem is when i try to add the other data from the mysql table: comment, name, date etc.
I have to replace these numbers with:
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo $name; ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
I tried this but it does not work and i didn't got much about arrays....
A little explaining would help me understand the concept better :)
$id_post = "1";
$name = array();
$email = array();
$comment = array();
$date = array();
//WHERE id_post = '$id_post'
$sq = mysql_query("SELECT * FROM article_comments WHERE id_post = '$id_post' ") or die(mysql_error());;
connect();
while($row = mysql_fetch_assoc($sq)){
$result[$row["parent_id"]][] = $row["id"];
$comment[$row['id']] = $row['comment'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
// $grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
}
$rowIsOpened = false; //Indicates whether a row is currently opened.
//I'm using $rowIsOpened because the row immediately after the rowspanned cell shouldn't be closed.
echo <<<HTML
<table style="border-color: black;border-style: solid;">
<thead>
<tr>
<th>Parent</th>
<th>Children</th>
</tr>
</thead>
<tbody>
HTML;
//Echo a bunch of HTML before actually looping
foreach ($result as $parent => $children) {
echo "<tr style='border-color: black;border-style: solid;vertical-align: top;'>";
echo "<td rowspan=";
echo count($children); //Span over <how many children are> rows
echo " style='border-color: black;border-style: solid;width:400px;' >$parent
<div class='cmt-cnt'>
<img src='".$grav_url."' />
<div class='thecom'>
<h5>".$name."</h5><span data-utime='1371248446' class='com-dt'>".$date."</span>
<br/>
<p>
".$comment."
</p>
</div>
</div>
</td>";
$rowIsOpened = true; //Row is opened
foreach ($children as $child) {
if (!$rowIsOpened) {
echo "<tr>";
} //Only open a row if row is not opened
echo "<td style='border-color: black;border-style: solid;width:400px;'>$child</td>";
echo "</tr>";
$rowIsOpened = false; //Row is now closed. Ready for next iteration.
}
}
//Close the table tags etc.
echo <<<HTML
</tbody>
</table>
HTML;
?>
You can add the entire result array to your parent array like this:
// I like to declare my variables and arrays
$results = array();
while ($row = mysql_fetch_assoc($sq)){
// I don't like to assume that I can append to array indexes that don't exist
if (!array_key_exists($row['parent_id'], $results)){
$results[$row['parent_id']] = array();
}
$results[$row['parent_id']][] = $row;
}
Then when you output, you can do this:
foreach ($results as $parent_id => $children){
// I'm leaving out the table because this is just for an example
echo $parent_id . '<br>';
foreach ($children as $child){
echo ' - ' . $child['commment'] . '<br>';
echo ' - ' . $child['date'] . '<br>';
}
}

Dynamically generate table using PHP

I know this has been asked before and I have got it working using the following code:
<?php
$maxcols = 8; $i = 0;
echo "<table id='table1'><tr>";
foreach ($id as $k => $v) {
echo "<td id='0'><div id='{$k}' class='drag t1'>{$v}</div></td>"; $i++;
if ($i == $maxcols) { $i = 0; echo "</tr><tr>"; }
} $i++;
while ($i <= $maxcols) {
$i++; echo "<td></td>";
}
echo "</tr></table>";
?>
This results in a table that looks like this :
I'd like to add headers to this so the end result looks like this:
I'd like to do it dynamically so if I create a table that is only 5 columns wide I'd get on the first header row ID01 - ID05 and on the second header row ID06 - ID10
I want to limit the header ID values to be no more than $maxid any extra header fields should be blank, like this : If $maxid = 12; then :
I need the header rows are made as follows and not using <TH>
<td class="mark">
I'm using some javascript to allow the movement of cell data.
The class is used to set the formatting on the header and stop items from being dragged into the fields.
Can anyone point me in the right direction on how to do this.
This should help you.
$maxcols = 8;
$maxid = 12;
$startid = 1;
echo "<table id='table1'>\n";
for ($i = 1;$i<=ceil($maxid/$maxcols);$i++) {
echo "<tr>\n";
for ($j=1;$j<=$maxcols;$j++)
if ($startid <= $maxid)
echo " <td class='mark'>ID".$startid++."</td>\n";
else
echo " <td> </td>\n";
echo "</tr>\n<tr>\n";
for ($j=1;$j<=$maxcols;$j++)
echo "<td>Content</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
Generates
<table id='table1'>
<tr>
<td class='mark'>ID1</td>
<td class='mark'>ID2</td>
<td class='mark'>ID3</td>
<td class='mark'>ID4</td>
<td class='mark'>ID5</td>
<td class='mark'>ID6</td>
<td class='mark'>ID7</td>
<td class='mark'>ID8</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td class='mark'>ID9</td>
<td class='mark'>ID10</td>
<td class='mark'>ID11</td>
<td class='mark'>ID12</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</table>
try this. It will work in the same way as you desired
<?php
$id= array("1","2","3","4","5","6","7","8","9","10","11","12");
$maxcols = 8; $i = 0;$j=0;$t=0;$s=0;
$maxid = count($id);
echo "<table id='table1'><tr>";
foreach ($id as $k => $v)
{
if($t == 0)
{
while ($t <= $maxcols-1) {
if($s < $maxid)
{
$s++;$t++; echo "<td class='mark'>id$s</td>";
}
else
{
echo "<td class='mark'></td>";$t++;$s++;
}
}
echo "</tr><tr>";
}
else
{
}
echo "<td id='0'><div id='{$k}' class='drag t1'>{$v}</div></td>"; $i++;
if ($i == $maxcols)
{
echo "</tr><tr>";
if($j == 0)
{
while ($j <= $maxcols-1) {
if($s < $maxid)
{
$s++;$j++; echo "<td class='mark'>id$s</td>";
}
else
{
echo "<td class='mark'></td>";$j++;$s++;
}
}
echo "</tr><tr>";
}
$i=0;
}
}
echo "</tr></table>";
?>
Output
Hi You can Use My Library:
class generate{
private $row = "<tr>{columns}</tr>";
private $td = "<td {attr}>{data}</td>";
private $attributeTR="";
private $attributeTD="";
private $tdBuilder="";
public function addCol($ColumValsArr=array("class='motota'"=>"Example")){
foreach($ColumValsArr as $key=>$val){
$newCol = str_replace("{data}",$val,$this->td);
$newCol = str_replace("{attr}",$key,$newCol);
$this->tdBuilder .= str_replace("{data}",$key,$newCol);
}
}
public function getRow(){
return str_replace("{columns}",$this->tdBuilder,$this->row);
}
}
<?php
function TableFunc($Data)
{
$Table = "<table>" . PHP_EOL;
foreach ($Data as $tags => $array) {
$Table .= "<$tags>" . PHP_EOL;
foreach ($array as $thead) {
$tag=$tags==="tbody"?"td":"th";
$Table .= "<tr>" . PHP_EOL;
if (is_array($thead)) {
foreach ($thead as $theadItem) {
if (is_array($theadItem))
$Table .= "<$tag colspan='$theadItem[1]'>$theadItem[0]</$tag>" . PHP_EOL;
else
$Table .= "<$tag>$theadItem</$tag>" . PHP_EOL;
}
}
$Table .= "</tr>" . PHP_EOL;
}
$Table .= "</$tags>" . PHP_EOL;
}
$Table .= "</table>" . PHP_EOL;
return $Table;
}
$Data = array(
"thead" => [
[["GENEL BİLGİ", 2], ["KALORİMETRE (ISINMA)", 2], ["HESAPLAMA", 2]],
["NO", "AD SOYAD", "FARK", "TUTAR", "OKUMA", "ÖDENECEK"]
],
"tbody"=>array(
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
),
"tfoot" => [["NO", "AD SOYAD", "M2", "MAHSUP", "SAYAÇ", "15°", "FARK", "TUTAR", "ORTAK ALAN", "EKSTRA", "MUAFİYET", "OKUMA", "ÖDENECEK"]]
);
echo TableFunc($Data);

How to make 4 items in a row using while loop?

I'm trying to display my products from the database. I'm trying to split it using the if 4%=0, but I can't get it to display 4 items in a row.
Here is my codes:
<table>
<tr>
<?php
include "connect_to_mysql.php";
$split = 0;
$display_all = mysql_query("SELECT * FROM products
ORDER BY FIELD(category, 'ipad','iphone','others')");
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
$split++;
if ($split%4==0){
echo '</tr><tr>';
}
?>
<td>
<table class="normal_text" align="center">
<tr>
<td><a href="product.php?product_id=<?php echo $id?>">
<img width="200px" height="133px" src="products/<?php echo $product_code?>.jpg" />
</a></td>
</tr>
<tr>
<td align="center" style="font-weight:bold"><?php echo $title;?></td>
</tr>
<tr>
<td align="center">$<?php echo $price;?></td>
</tr>
</table>
</td>
<?php
}
?>
</tr>
</table>
You've got the PHP logic before, rather than inside your HTML table output.
Try reorganizing like this:
<?php
include "connect_to_mysql.php";
$split = 0;
$display_all = mysql_query("SELECT * FROM products
ORDER BY FIELD(category, 'ipad','iphone','others')");
?>
<table class="normal_text" align="center">
<tr>
<?php
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
// output product details -- note use of quotes to include PHP vars
$rowHTML = "<td><a href='product.php?product_id=$id'>";
$rowHTML .= "<img width='200px' height='133px' src='products/$product_code.jpg' />";
$rowHTML .= "</a><br/>";
$rowHTML .= "<strong>$title</strong>";
$rowHTML .= "$price</td>";
echo $rowHTML;
$split++;
if ($split%4==0){
echo '</tr><tr>';
}
}
?>
</tr>
</table>
while($row=mysql_fetch_assoc($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
if ($split % 4 === 0) echo "\n<tr>";
?>
// ONLY <td> CODE </td> here. NO <tr> and NO </table>
<?php
if ($split % 4 === 3) echo "</tr>";
$split++;
}
?>
You are starting and ending at same time and then putting table for each.
You want to start <tr> when %4==0 and end </tr> when %4==3.
Rather than use modulus (%), just add a second variable called $cols, assign it to the amount of columns you want, and compare it. For example:
$rows = 1;
$cols = 4;
$display_all = mysql_query("SELECT * FROM products ORDER BY FIELD(category, 'ipad','iphone','others')");
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
$split++;
if ($rows==$cols){
echo '</tr><tr>';
$rows = 1;
}

Can each row in an HTML table be numbered?

What I would like to do is number each row in my table. I can't manually number the table myself, as all of the info in it is retrieved from a database. Is this possible with jQuery or PHP? Here's a screen shot of the table:
I tried searching for this, and did not find anything that helped me.
Here is the PHP / HTML that is displaying the table:
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Created on</th>
<th style="width:65px;">Status</th>
<th>Actions</th>
</tr>
<?php
[...]
//Display the results
while($info = mysql_fetch_assoc($result)){
//data
$name = $info['name'];
$email = $info['email'];
$subject = $info['subject'];
$ticketid = $info['ticket'];
$isActive = $info['is_active'];
$created = $info['created'];
//status
if($isActive == "1") {
$status = "<span class=\"open\">Open</span>";
$status2 = "active";
}
else if($isActive == "0") {
$status = "<span class=\"closed\">Closed</span>";
$status2 = "closed";
}
else {
$status = "";
}
echo "
<tr>
<td style=\"min-width: 87px;\">$name</td>
<td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td>
<td title=\"$subject\">".addEllipsis($subject, 18)."</td>
<td style=\"width: 235px;\">$created</td>
<td title=\"This ticket is $status2\">$status</td>
<td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket »</a></td>
</tr>
";
}
As you can see, it's displayed with a while loop.
If anyone knows a way to number each line in my table with jQuery or PHP, please help me :)
$trCounter=0;
while($info = mysql_fetch_assoc($result)){
//data
$name = $info['name'];
$email = $info['email'];
$subject = $info['subject'];
$ticketid = $info['ticket'];
$isActive = $info['is_active'];
$created = $info['created'];
//status
if($isActive == "1") {
$status = "<span class=\"open\">Open</span>";
$status2 = "active";
}
else if($isActive == "0") {
$status = "<span class=\"closed\">Closed</span>";
$status2 = "closed";
}
else {
$status = "";
}
echo "
<tr>
<td>$trCounter++</td>
<td style=\"min-width: 87px;\">$name</td>
<td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td>
<td title=\"$subject\">".addEllipsis($subject, 18)."</td>
<td style=\"width: 235px;\">$created</td>
<td title=\"This ticket is $status2\">$status</td>
<td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket »</a></td>
</tr>
";
}
or you could always use the :eq api in your jquery selector or its equivalent to work with the index but like I asked it depends on what you want to do with the index.
I would go with PHP solution listed by Atul Gupta.
To add more - you also can to start iteration based on which page you are.
<?php
$i = ($page-1) * $itemsPerPage;
while(....)
{
echo $i;
$i++;
}
?>
if you are on the second page of your list would get something like 11,12,13,14,....
jQuery:
$(function () {
var i = 0;
$('table thead tr').prepend('<th>#</th>');
$('table tbody tr').each(function () {
i += 1;
$(this).prepend('<td>' + i + '</td>');
});
});
PHP
<tr>
<th>Sr. No</th> // Add header for counter
<th>Name</th>
...
</tr>
...
$i=1; // add counter -----------corrected-------------
while($info = mysql_fetch_assoc($result)){
//data
...
echo "
<tr>
<td>$i</td> // include counter to table
<td style=\"min-width: 87px;\">$name</td>
...
</tr>
";
$i++; // increment counter
}
Set an auto increment property in the SQL table, which can be used as an index, and will increase automatically when a new entry is added?

Categories