Table Structure Php Matrix Grid - php

I would like to create a matrix grid using widths and drops from the database.
The price would need to be displayed in the associated width and drop cell.
For example:
width x drop: 600 700 800 900
600 226
700 236
800 248
900 290
Some values will be not be there as the product instance has not been created.
I have three tables:
1) product_instance (id, product_name, width_id, drop_id, price)
2) product_width (id, width)
3) product drop (id, drop)
This is what I have so far:
<table>
<thead>
<tr>
<th>w x d</th>
<?
$query = "SELECT * FROM product_instance
INNER JOIN product_width ON product_instance.width_id
= product_width.width_id
INNER JOIN product_drop ON product_instance.drop_id =
product_drop.drop_id
INNER JOIN products ON product_instance.product_id =
products.product_id WHERE product_instance.product_id
= 1";
$select_products = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($select_products)) {
$width_value = $row['width_value'];
echo "<th>$width_value</th>";
}
?>
</tr>
</thead>
<tbody>
<?
$query = "SELECT DISTINCT * FROM product_instance
INNER JOIN product_width ON
product_instance.width_id
= product_width.width_id
INNER JOIN product_drop ON product_instance.drop_id =
product_drop.drop_id
INNER JOIN products ON product_instance.product_id =
products.product_id WHERE product_instance.product_id
= 1";
$select_products = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($select_products)) {
$drop_value = $row['drop_value'];
$price = $row['price'];
echo "<tr>";
echo "<td>$drop_value</td>";
echo "<td>$price</td>";
echo "</tr>";
}
?>
</tbody>
</table>
I'm not sure how to do this and have looked around but cant find a solution.

I managed to find a workable solution using PHPivot
My code now looks like this:
<?php
require 'pivot/PHPivot.php';
//Get the data
//Could be from a database, JSON, etc
$query = "SELECT * FROM product_instance
INNER JOIN product_width ON product_instance.width_id =
product_width.width_id
INNER JOIN product_drop ON product_instance.drop_id =
product_drop.drop_id
INNER JOIN products ON product_instance.product_id =
products.product_id WHERE product_instance.product_id = 1";
$select_products = mysqli_query($connection, $query);
$result = [];
$counter = 0;
while ($row = mysqli_fetch_array($select_products)) {
$menu[$counter] = array(
"width" => $row['width_value'],
"price" => $row['price'],
"drop" => $row['drop_value']
);
array_push($result,$menu[$counter]);
$counter ++;
}
$data = $result;
//Just needs to be saved in an associative PHP array
$products = PHPivot::create($data)
->setPivotRowFields('width')
->setPivotColumnFields('drop')
->setPivotValueFields('price',PHPivot::PIVOT_VALUE_SUM,
PHPivot::DISPLAY_AS_VALUE, 'Drop')
->addFilter('width', '', PHPivot::COMPARE_NOT_EQUAL)
//Filter out blanks/unknown genre
->generate();
echo $products->toHtml();
?>

Related

Selecting only amount with values greater than 0 in sql

I have this table
The table contains amount with values that has both negative and positive signs. I was able to fetched the sum of positive amount but after the sumation I have zero values which I don't want to show - it fetched all values.
Objective: fetch sum of amount and return amount with no zero values.
What I tried so far
$ques = "select * from company";
$checks22y = sqlsrv_query($conn, $ques);
$row22y = sqlsrv_fetch_array($checks22y, SQLSRV_FETCH_ASSOC);
$daty = $row22y['BRSES_DATE']->format('Y-m-d H:m:i');
$com = $row22y['branch'];
$query = "SELECT distinct ".$limitresult." Member.Branch,Member.GL_No,Member.Ac_NO,Member.BRANCH+Member.GL_NO+Member.AC_NO
AS BRGLAC,Customer.Cust_No,Customer.Name,Group_Name,ID_CARD,Subgroup as subgroup2,
Cust_Type,Cust_Sex,Cust_Cat,Area_Code,Cust_Type,Dobirth,Address,Ref_No,Bank_VNO,Cust_Ca2,
nType,Group_Code FROM Member INNER JOIN CUSTACC ON Member.Branch = CustAcc.Branch AND
Member.GL_NO = CustACC.GL_No AND Member.AC_NO = CustACC.AC_No
INNER JOIN Customer ON Member.Branch = Customer.Branch ".$branchid." AND Member.Cust_No = Customer.Cust_No ".$accnos." WHERE
CUSTACC.Exp_Date < '$daty' AND MEMBER.Gl_NO IN (SELECT Coa.GL_NO FROM Coa WHERE Product = 'S' ) AND cust_type IN ('IND','GRP','MEM') ";
$check = sqlsrv_query($conn, $query);
$i = 1;
while($rows = #sqlsrv_fetch_array( $check, SQLSRV_FETCH_ASSOC)) {
$ac = $rows['Ac_NO'];
$br = $rows['Branch'];
//Second sub query
$get ="select ac_no, gl_no, SUM(amount) as OutBalance,MAX(Batch_Date) AS Last_Trx2 from memtrans where gl_no like '2001%'
and ac_no='$ac' group by ac_no, gl_no HAVING SUM(amount) > 0
";
$check2 = sqlsrv_query($conn, $get);
$rowb = sqlsrv_fetch_array( $check2, SQLSRV_FETCH_ASSOC);
//Third sub query, OD history
$od = "select od_limit from custacc where ac_no='$ac' and od_limit > '0'";
$odc = sqlsrv_query($conn, $od);
$rowbo = sqlsrv_fetch_array( $odc, SQLSRV_FETCH_ASSOC);
}
The outcome
If you look at the Outstanding Balance you will see zero values appearing.
The secon sub query is where the fetching of Outstanding Balance took place.
Just solved it.
Here is the query I later used:
SELECT distinct ".$limitresult." member.Branch,Member.GL_No,Member.Ac_NO,Member.BRANCH+Member.GL_NO+Member.AC_NO
AS BRGLAC,Customer.Cust_No,Customer.Name,Group_Name,ID_CARD,Subgroup as subgroup2,Cust_Type,Cust_Sex,Cust_Cat,Area_Code,Cust_Type,Dobirth,Address,Ref_No,Bank_VNO,Cust_Ca2,nType,Group_Code, SUM(memtrans.amount) as OutBalance,MAX(memtrans.Batch_Date) AS Last_Trx2,company.BRSES_DATE, company.branch, CustACC.od_limit FROM Member INNER JOIN CUSTACC ON Member.Branch = CustAcc.Branch AND Member.GL_NO = CustACC.GL_No AND Member.AC_NO = CustACC.AC_No INNER JOIN Customer ON Member.Branch = Customer.Branch AND Member.Cust_No = Customer.Cust_No INNER JOIN memtrans ON memtrans.ac_no = member.ac_no INNER JOIN company ON company.branch = member.branch ".$branchid." ".$accnos." WHERE CUSTACC.Exp_Date < company.BRSES_DATE AND CUSTACC.od_limit > '0.00' AND MEMBER.Gl_NO IN (SELECT Coa.GL_NO FROM Coa WHERE Product = 'S' ) AND cust_type IN ('IND','GRP','MEM') group by memtrans.ac_no, memtrans.gl_no,company.branch, member.branch, member.gl_no,Member.ac_no,
Customer.cust_no, Customer.name, Customer.group_name,Customer.id_card,Customer.subgroup,Customer.cust_type,
Customer.cust_sex, Customer.cust_cat,Customer.area_code,Customer.dobirth,Customer.address,Customer.ref_no, Customer.Bank_VNO,Customer.cust_ca2,Customer.ntype,Customer.group_code,company.BRSES_DATE,CUSTACC.od_limit HAVING SUM(memtrans.amount) > 0)
Thanks guys. From a grateful heart.

PHP SQL inner Join bool(false)

I am attempting to get a 'total weight' for items a character is carrying. I am doing this by selecting the quantity of items in the characteritem table and comparing the weight which is set in the item table and they are joined by the iid (item id) column
I have tried a lot of different methods to no avail so I have looked up join statements. The issue I have is why the $result would return bool(false) and then how I can get the weights to add up afterwards.
Here is the code I am working with currently:
$sql = "SELECT *
FROM `characteritem` WHERE `owner` = '$user'
INNER JOIN item ON characteritem.iid=item.iid";
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$iid = $row['characteritem.iid'];
$quantity = $row['characteritem.quantity'];
$itemweight = $row['item.itemweight'];
$itemtotal = $itemweight + $itemweight;
echo $itemtotal;
}
}
var_dump($result);
SQL is working fine now. I have got the weight and quantity and gotten the individual results. How would I get the values to add together for $itemtotal?
$sql = "SELECT *
FROM `characteritem`
INNER JOIN item ON characteritem.iid=item.iid
WHERE `owner` = '$user'";
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$iid = $row['characteritem.iid'];
$quantity = $row['quantity'];
$itemweight = $row['itemweight'];
$itemtotal = $itemweight * $quantity;
echo $itemtotal;
}
}
Your SQL sintax is wrong, try
$sql = "SELECT *
FROM `characteritem`
INNER JOIN item ON characteritem.iid=item.iid
WHERE `owner` = '$user'";
Try This
$sql = "SELECT *
FROM `characteritem`
INNER JOIN item ON characteritem.iid=item.iid" WHERE `owner` = '$user';
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$iid = $row['characteritem.iid'];
$quantity = $row['characteritem.quantity'];
$itemweight = $row['item.itemweight'];
$itemtotal = $itemweight + $itemweight;
echo $itemtotal;
}
}
var_dump($result);

Putting data from two different loops in a google pie chart

So I have this code for my Google pie chart (pie chart code not included, but it works fine and displays data)
<?php
$query = "SELECT * FROM category WHERE type = 'Expense' ";
$select_category_list = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_category_list)) {
$cat_id = $row['id'];
$cat_title = $row['title'];
echo "['$cat_title'" . ",";
echo "$cat_id],";
}
?>
I put the echo in different lines, but it really does not matter to if they are in one line or in two lines, what matters is to get it finally working :)
Instead of $cat_id I want to put the SUM ($cat_amount) calculated by this code:
$query = "SELECT category_id, SUM(amount) AS TotalAmount FROM spendee
WHERE type = 'Expense' group by category_id ";
$expense_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($expense_query)) {
$cat_amount = $row['TotalAmount'];
}
I have tried putting while loop in a while loop, foreach loop in a while loop, putting $cat_amount instead of $cat_id (that only displays one SUM) and so on. Nothing worked. I have not tried the for loop, but I assume the result would be the same + I am not sure how would I define the times that the loop needs to run, since there could be many type 'Expense' categories added in time.
Any help would be very much appreciated. Thank you and have a lovely day.
maybe i'm missing something, but looks like you could join the two tables in one query
this would get the desired result in one query / loop...
sql:
SELECT a.title as Title, SUM(b.amount) AS TotalAmount FROM category a, spendee b WHERE b.category_id = a.id and b.type = 'Expense' group by a.title
php:
<?php
$query = "SELECT a.title as Title, SUM(b.amount) AS TotalAmount FROM category a, spendee b WHERE b.category_id = a.id and b.type = 'Expense' group by a.title";
$select_category_list = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($select_category_list)) {
$cat_title = $row['Title'];
$cat_amount = $row['TotalAmount'];
echo "['$cat_title'" . ",";
echo "$cat_amount],";
}
?>

Get highest sum value from two tables

Here is my code:
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
<tr> <?php echo $sum; ?></tr>
}while($row_query1 = mysql_fech_assoc($result));
I need to get the highest value of $sum from this loop. Can anyone help?
You can do like this.. take a temporary variable($temp) which can have check upon the sum variable($sum).
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
$temp = 0;
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
if($temp < $sum)
$temp = sum;
echo "<tr>$sum</tr>";
}while($row_query1 = mysql_fech_assoc($result));
echo "maximum sum :".$temp;
I would advice doing a JOIN instead of performing the sub queries yourself:
select user, sum(column) + sum(column1) as total
from table1
INNER JOIN table2 ON names = user
GROUP BY user
The rest should be straightforward in code.

How to get rid of several while loops and a better idea of displaying results

My application requires to create a stock management table which has a lot of items categorised into subgroups. For and idea, the stock management table looks like:
Location1 Location2 Total
Desktops // Main Category
Microsoft //Sub-Category
Windows 7 23000 150000 173000
Office 2011 203300 3002 206302
....
Apple //Sub-Category
OS Snow Leopard 4000 3000 7003
OS Lion 39494 40034 79528
...
Tablets //Main Category
Lenovo //Sub-Cateogry
LX-243 3434 4399 7833
...
This is a visualisation of what the table should look like, now i have a huge mysql query which does that for me, it is scary. In a gist, what i am doing is the following:
Select 1st category and start a while loop
// echo as the main category
Select sub-category corresponding to the main category and start a while loop again.
// echo as the sub-category
select all items in the sub-category and start a while loop.
select 1st location.
select the current item from 3 and the current location from 4 and echo item.
// echo item names and the quantity in the locations.
Now my question here is is there a better way to display this than using several while loops, i tried using functions but they are becoming a mess too. Also i couldn't figure out where should i perform the calculations to get the total in the last column.
Database structure:
Category: CategoryID, Description
Sub-Cateogry: Sub-Category_ID, Category_ID, Description
Item: Item_ID, Sub-category_id, Description
Location: Location_ID, Description
Stock_Management: Item_ID, Location_ID, Quantity
Code as requested:
$sql = mysql_query("select Board_ID, Title from Board where Company_ID = '$company_id' order by Title");
while($row = mysql_fetch_array($sql)) {
$curr_ID = $row[0];
$curr_category = $row[1];
echo "<tr class='sub-heading' style='background: rgba(76, 178, 255, 0.1)'><td colspan='".$count."'>".$curr_category."</td></tr>";
$sql1 = mysql_query("select Sub_Category_ID, Title from Sub_Category where Category_ID = '$curr_ID' order by Title");
while($row1 = mysql_fetch_array($sql1)) {
$curr_sub_cat_id = $row1[0];
$curr_sub_cate = $row1[1];
echo "<tr style='background: rgba(149, 255, 145, 0.10'><td colspan='".$count."'><b>".$curr_sub_cate."</b></td></tr>";
$sql2 = mysql_query("select Book_ID, title from Book where sub_category_id = '$curr_sub_cat_id' Order by title");
while($row2 = mysql_fetch_array($sql2)) {
$curr_book = $row2[0];
echo "<tr><td>".$row2[1]."</td>";
$sql4 = mysql_query("select OfficeID, OfficeTitle from Office where OfficeTitle IN ('$locations')");
while($row3 = mysql_fetch_array($sql4)) {
$curr_location = $row3[0];
$sql3 = mysql_query("select Quantity from Stock_Management where Book_ID = '$curr_book' and Location_ID = '$curr_location'");
while($row3 = mysql_fetch_array($sql3)) {
echo "<td>".$row3[0]."</td>";
}
}
echo "</tr>";
}
}
}
How about something like this -
<?php
$locations = array('Location 1', 'Location 2', 'Location 3');
$locationCols = array();
$locationList = array();
foreach ($locations as $location) {
$locationColName = preg_replace('[^a-z0-9]', '_', strtolower($location));
$location = mysql_real_escape_string($location);
$locationCols[] = "SUM(IF(Office.OfficeTitle = '$location', Stock_Management.Quantity, 0)) AS `$locationColName`";
$locationList[] = "'$location'";
}
$locationCols = implode(', ', $locationCols);
$locationList = implode(',', $locationList);
$sql = "SELECT Board.Title AS BoardTitle, Sub_Category.Title AS SubCatTitle, Book.title AS BookTitle, $locationCols, SUM(Stock_Management.Quantity) AS Total
FROM Board
INNER JOIN Sub_Category
ON Board.Board_ID = Sub_Category.Category_ID
INNER JOIN Book
ON Sub_Category.Sub_Category_ID = Book.sub_category_id
INNER JOIN Office
LEFT JOIN Stock_Management
ON Book.Book_ID = Stock_Management.Book_ID
AND Office.OfficeID = Stock_Management.Location_ID
WHERE Board.Company_ID = 2
AND Office.OfficeTitle IN ($locationList)
GROUP BY Board.Title, Sub_Category.Title, Book.title";
$result = mysql_query($sql);
$prevBoard = '';
$prevSubCat = '';
echo '<table>';
while ($row = mysql_fetch_object($result)) {
// if new board print board
if ($prevBoard != $row->BoardTitle) {
echo '<tr class="sub-heading" style="background: rgba(76, 178, 255, 0.1)"><td colspan="">' . $row->BoardTitle . '</td></tr>';
}
$prevBoard = $row->BoardTitle;
if ($prevSubCat != $row->SubCatTitle) {
echo '<tr style="background: rgba(149, 255, 145, 0.10)"><td colspan=""><b>' . $row->SubCatTitle . '</b></td></tr>';
}
$prevSubCat = $row->SubCatTitle;
// print product row
echo '<tr>';
echo "<td>{$row->BookTitle}</td>";
foreach ($locations as $location) {
$locationColName = preg_replace('[^a-z0-9]', '_', strtolower($location));
echo "<td>{$row->$locationColName}</td>";
}
echo "<td>{$row->Total}</td>";
echo '</tr>';
}
echo '<table>';

Categories