I want to fetch and echo item from MySQL database multi-times according to session quantity.
Example :
id | qty | item
1 | 2 | shoe
2 | 4 | net
3 | 3 | phone
My result set should be like this :
shoe, shoe
net, net, net, net
phone, phone, phone
I tried :
if(isset($_SESSION["cart_products"]))
foreach ($_SESSION["cart_products"] as $each_item){
$item_id = $each_item['item_id'];
$qty = $each_item['quantity'];
$sql = mysql_query("SELECT * FROM products WHERE id='$item_id' ORDER BY id");
$qty = array();
while ($row = mysql_fetch_array($sql)) {
$qty[] = $row;
}foreach($qty as $row){
$product_name = $row["product_name"];
}
echo'$product_name';
Any help is appreciated.
if(isset($_SESSION["cart_products"]))
foreach ($_SESSION["cart_products"] as $each_item){
$item_id = $each_item['item_id'];
$qty = $each_item['quantity'];
$sql = mysql_query("SELECT * FROM products WHERE id='$item_id'
ORDER BY id");
while ($row = mysql_fetch_array($sql)) {
$qty = $row['qty'];
for($i=0; $i < $qty; $i++){
echo $row['item'].' ';
}//end for
echo '<br>';//go to next-line
}//end while
}//end foreach
Related
I have two tables. One of them is called "customer" and the other is "current account".
I want to do; To collect the debit and credit columns in the current account table of data recorded in the customer table and draw the result. But somehow I cannot do the correct calculation. I leave my sample codes below.
Thank you in advance for your support.
Table Name : Customer Table name : Current Account
| tax | company_name |tax_no| debt | take
______________________ _________________________
| 1234| Company One |1234 | 9 |
| 5678| Company Second |1234 | | 3
|1234 | 15 |
|5678 | 4 |
|5678 | | 1
According to the table above, what I want to do is combine the data in the current account table according to the data in the customer table, take the debt from the receivable and get the result.
// Data list
$sql = $db->query("SELECT*FROM customer ORDER BY company_name ASC");
$sum_debt = 0;
$sum_take = 0;
foreach($sql->results() as item){
$tax = $item->tax;
$current = $db->query("SELECT*FROM current_account WHERE tax_no = '$tax' ");
foreach($current->results() as $row){
$sum_debt += $row->debt;
$sum_take += $row->take;
$res = $sum_take - $sum_debt;
}
}
The result is always wrong. It makes the conclusion by making the correct operation of the first data. It collects the first result over the next data.
The results that should be obtained according to the table; company one is: -24, company second is -3, but the second data is -27.
If you want to calculate the total per company, you should reset the debt and take for every new company and move the $res = $sum_take - $sum_debt; line from the inner foreach to the outer foreach and save the result for every company it is calculated.
// Data list
$sql = $db->query("SELECT*FROM customer ORDER BY company_name ASC");
$sum_debt = 0;
$sum_take = 0;
foreach($sql->results() as item)
{
$sum_debt = 0;
$sum_take = 0;
$tax = $item->tax;
current = $db->query("SELECT*FROM current_account WHERE tax_no = '$tax' ");
foreach($current->results() as $row){
$sum_debt += $row->debt;
$sum_take += $row->take;
}
$res = $sum_take - $sum_debt;
//Save or print res
echo $tax . " has debt: " . $res;
}
I would also highly recommend to retrieve all the nescessary calculated data within the first SQL query. Doing a query per company can be expensive and result in poor performance. The SQL would be something like:
SELECT c.tax,
c.company_name,
(SELECT SUM(take) FROM [Current Amount] WHERE tax_no = tax) -
(SELECT SUM(debt) FROM [Current Amount] WHERE tax_no = tax) AS [res]
FROM Company
If $res should contain the current account balance of a customer you need to move the calculation of $res outside of the inner for-loop and reset the sum_debt and sum_take for each customer:
$sql = $db->query("SELECT*FROM customer ORDER BY company_name ASC");
//for loop for each customer
foreach($sql->results() as item){
$sum_debt = 0; //debt of this customer
$sum_take = 0; //credit of this customer
$tax = $item->tax;
$current = $db->query("SELECT*FROM current_account WHERE tax_no = '$tax' ");
foreach($current->results() as $row){
$sum_debt += $row->debt;
$sum_take += $row->take;
}
$res = $sum_take - $sum_debt; //account balance of this customer
}
Also you could simplify your code by directly calculating the account balance:
$sql = $db->query("SELECT*FROM customer ORDER BY company_name ASC");
//for loop for each customer
foreach($sql->results() as item){
$balance_of_this_customer = 0;
$tax = $item->tax;
$current = $db->query("SELECT*FROM current_account WHERE tax_no = '$tax' ");
foreach($current->results() as $row){
$balance_of_this_customer -= $row->debt;
$balance_of_this_customer += $row->take;
}
}
I think you could do this in one SQL query and no query in a loop.
SELECT customer.company_name, customer.tax, SUM(current_account.debt) AS total_debt, SUM(current_account.take) AS total_take FROM customer LEFT JOIN current_account ON current_account.tax_no = customer.tax GROUP BY customer.tax
try this. i've fixed your problem and edited your code with better syntax, ofcourse in myself opinion
$data = array();
$customers = $db->query("SELECT * FROM `customer` ORDER BY `company_name` ASC");
$customers = $customers->results();
$result = 0;
foreach($customers as $customer){
if(!isset($data[$customer['id']])){
$data[$customer['id']] = array(
'balance' => 0,
'debt' => 0,
'take' => 0
);
}
$accounts = $db->query("SELECT * FROM `current_account` WHERE `tax_no` = '" . $customer->tax . "'");
$accounts = $accounts->results();
foreach($accounts as $account){
$data[$customer['id']]['take'] += $row->take;
$data[$customer['id']]['debt'] += $row->debt;
$data[$customer['id']]['balance'] = $data[$customer['id']]['take'] - $data[$customer['id']]['debt'];
}
}
print_r($data);
I have a while loop that is supposed to first get the individual_id from a table called submittedresume using the job_id that it gets from another function. It would then use that id in another while loop to get the first_name and last_name from the individual table. It would then use another while loop to get the submitted_id from the submitted resume table.
I split the first and last while loop to get distinct values from the output.
My first while loop. It first gets the individual_id from a table called submittedresume using the job_id that it gets from another function. It gives me the correct output of two user ids: 9 and 4.
global $database;
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
while ($row = mysqli_fetch_array($output)) {
$indvId = $row[0];
}
This is the second inner while loop. It gives me an output of Mary Jane (No repeat) and Tom Sawyer.
$indvId = $row[0];
$sql = "SELECT * FROM individual WHERE individual_id='$indvId'";
$result = $database->query($sql);
while ($details = mysqli_fetch_array($result)) {
$first = $details['first_name'];
$last = $details['last_name'];
echo $first;
echo $last;
}
This is my whole function:
public function displayApplications($id){
global $database;
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
while ($row = mysqli_fetch_array($output)) {
$indvId = $row[0];
$sql = "SELECT * FROM individual WHERE individual_id='$indvId'";
$result = $database->query($sql);
while ($details = mysqli_fetch_array($result)) {
$first = $details['first_name'];
$last = $details['last_name'];
$sqlquery = "SELECT DISTINCT resume_title FROM submittedresume WHERE individual_id='$indvId' order by submitted_id";
$data = $database->query($sqlquery);
if (mysqli_num_rows($data) == 0) {
echo "Database is empty <br>";
} else {
while (($name = mysqli_fetch_array($data))) {
echo $first . " " . $last . " "."<a href=handleDownload.php?id=$id>$name[0]</a><br>";
}
}
}
}
}
This is what I'm getting right now:
first_name | last_name | resume_name
Mary | Jane | resume_1
Mary | Jane | resume_2
This is what I'm looking for:
first_name | last_name | resume_name
Mary | Jane | resume_2
Tom | Sawyer | resume_1
I think after while use foreach loop:
For example:
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
$details = mysqli_fetch_array($result);
foreach($details as $key => $value){
echo 'Key: '. $key . ' '. 'Value: '. $value;
}
$indvId = $row[0]; is returning the 1st item in the result array
I personally would use a foreach loop but you could do it the way you have it by adding a counter ie: $count = 0; before the loop and $count++; inside the loop and $indvId = $row[$i];
I have a table containing the following records:
product_id | title | category
------------------------------------
1 | apple | mobile
2 | android | mobile
3 | dell | desktop
4 | hp | desktop
and the following query:
$sql = "SELECT product_id, title, category FROM products ORDER BY category";
$stmt = $db->prepare($sql);
$stmt->execute();
while($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $results["product_id"];
echo $results["title"];
echo $results["category"];
}
The question is how to split the results and display all records in a list sorted by category as below:
Mobile
Apple
Android
Desktop
Dell
HP
Group your records after get the result set:
$products = array();
while ($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
$products[$results['category']][] = array(
'product_id' => $results['product_id'],
'title' => $results['title']
);
}
foreach ($products as $category => $productList)
{
echo $category . '<br>';
foreach ($productList as $product)
{
echo $product['title'] . '<br>';
}
echo '<hr />';
}
Use SELECT * FROM products GROUP BY category ORDER BY title
After sorting your items (ORDER BY category, title), do something like this:
$last_category = "";
while(/* get a row here */) {
if( $last_category != $row['category']) {
if( $last_category != "") echo "</ul>";
echo "<ul>";
$last_category = $row['category'];
}
echo "<li>".$row['title']."<li>";
}
if( $last_category != "") echo "</ul>";
SELECT * FROM products ORDER BY category. This is to sort using category, your example output file seems different what are you trying to do?
I have been trying to fureout how to create a dynamic multi dimensional array.
The reason for this is that I want to create a dropdown menu that will be created dynamically from the mysql
Sample database
|id|menu_name|menu_parent_id|
|1 |top menu1| 0 |
|2 |top menu2| 0 |
|3 |top menu3| 0 |
|4 |top menu4| 0 |
|5 |sub menu | 2 |
|6 |sub menu | 2 |
|7 |sub menu | 5 |
|8 |sub menu | 6 |
|9 |top menu | 0 |
I thought of starting from getting the menu with no parent then put it on an array
$parentIDs[0]=0;
$tempParentIDs = array();
$childIDs = array();
$menus = array();
$rows = 0;
$rows=0;
foreach($parentIDs AS $value){
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$value");
while($temp = mysql_fetch_array($sql)){
//$tempParentIDs[] = $temp['service_id'];
//check if parent have child
$sql2 = mysql_query("SELECT * FROM service WHERE service_parent_id=$temp[service_id]") or die(mysql_error());
$rows = mysql_num_rows($sql2);
if($rows >= 1){
//This means there is a child
while($temp2 = mysql_fetch_array($sql2)){
$childIDs[] = $temp2['service_id'];
}
$tempParentIDs[$temp['service_id']] = $childIDs;
unset($childIDs);
} else {
//This means there is no child
}
}
}
echo "<pre>";
print_r($tempParentIDs);
echo "</pre>";
but after then I'm stuck.
I think you are looking for this:
$parentIDs[0]=0;
$tempParentIDs = array();
$childIDs = array();
$menus = array();
$rows = 0;
$multiDimensionalArray = NULL; //here I made change - vijay
$rows=0;
foreach($parentIDs AS $value){
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$value");
while($temp = mysql_fetch_array($sql)){
$tempParentIDs = $temp['service_id']; //here I made change - vijay
//check if parent have child
$sql2 = mysql_query("SELECT * FROM service WHERE service_parent_id=$temp[service_id]") or die(mysql_error());
$rows = mysql_num_rows($sql2);
if($rows >= 1){
//This means there is a child
while($temp2 = mysql_fetch_array($sql2)){
$multiDimensionalArray[$tempParentIDs][] = $temp2['service_id']; //here I made change - vijay
}
// $tempParentIDs[$temp['service_id']] = $childIDs; //here I made change - vijay
// unset($childIDs); //here I made change - vijay
} else {
//This means there is no child
}
}
}
echo "<pre>";
print_r($multiDimensionalArray); //here I made change - vijay
echo "</pre>";
You should store array in php like this way :
This will maybe work for you
$next = 0;
$level = 0;
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$next");
$temps = array();
while($temp = mysql_fetch_array($sql))
{
$temps[] = $temp;
}
foreach($temps as $temp)
{
echo $temp['service_id'];
}
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>';