How to loop inside loops? - php

I have 2 table.
Table1 "Order"
orderid - customer_id
1001 - 1234
Table2 "Items"
no - orderid - items_code
1 - 1001 - 100
2 - 1001 - 200
3 - 1001 - 300
how to get results as below (in php):
Order # Items Customer ID
_________________________________________
1001 100, 200, 300 1234
_________________________________________
1002 400, 500, 600 1210
_________________________________________
1003 321, 654, 987 1256
_________________________________________
This is my previous coding:
<?
include("cat-config.php");
$resultdata=mysql_query("
(SELECT * FROM Order LIMIT 10)
");
echo "<table width=\"100%\" border=\"0\">
<tr>
<td>Order #</td>
<td>Items</td>
<td>Customer ID</td>
</tr>";
while($row=mysql_fetch_assoc($resultdata)){
echo "
<tr>
<td>$row[OrderID]</td>
<td>
**(I want loops items data on table "items": 100, 200,300 here)
</td>
<td>$row[CustomerID</td>
</tr>
";
}
mysql_close();
?>

$orders = array( 1001, 1002, 1003 );
for ( $i = 0; $i < count( $orders ); $i++ )
{
$items = getItemsForOrderId( $orders[$i] ); // SQL query or something
for ( $j = 0; $j < count( $items ); $j++ )
{
echo 'Order #' . $orders[$i] . ', Item ' . $items[$j];
}
}
Format to wanted output, and adjust to get the data correctly.
Update based on the changed question:
This could be one way to do it:
<?php
include 'cat-config.php';
$resultdata = mysql_query( 'SELECT * FROM Order LIMIT 10' );
echo "<table width=\"100%\" border=\"0\">
<tr>
<td>Order #</td>
<td>Items</td>
<td>Customer ID</td>
</tr>";
while ( $orderRow = mysql_fetch_assoc( $resultData ) )
{
echo " <tr>\n <td>" . $orderRow['orderid'] . "</td>\n";
echo " <td>";
$itemData = mysql_query( 'SELECT * FROM Items WHERE orderid = ' . $orderRow['orderid'] );
while ( $itemRow = mysql_fetch_assoc( $itemData ) )
{
echo $itemRow['items_code'] . ', ';
}
echo "</td>\n <td>" . $orderRow['customer_id'] . "</td>\n </tr>\n";
}

Easiest is to run it as 2 seperate queries:
SELECT * FROM Order
And while looping through results:
X = OrderID
SELECT * FROM Items WHERE OrderId = X

Related

How to calculate rank of the player with most money?

I am building a leaderboard which is built by joining two different databases, the most important is the wallet column which is what I'll use to rank the players. I need to add a column ranked from the player with most money to least amount of money. What is the best way to do this?
$result = mysqli_query($conn, "SELECT * FROM darkrp_player inner join playerinformation on (darkrp_player.uid = playerinformation.uid)");
Basically, you need to order by on your wallet column to short for showing most money to least amount of money of the user i.e DESC ordering. But if you want to get the rank number value of each user also apart from ordering you can do it this way with ROW_NUMBER() window function
SELECT *, rank FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY wallet DESC) as rank
FROM darkrp_player INNER JOIN playerinformation ON (darkrp_player.uid = playerinformation.uid)
) t
Expected Output: on $result variable
id other........columns wallet rank
1111 xyz............abc 100 1
2222 xyz............abc 90 2
3333 xyz............abc 80 3
alright these work! here's my code for anyone that might across something similar
<table class="table" data-order='[[ 0, "asc" ]]'>
<thead>
<tr>
<th>Place</th>
<th>Avatar</th>
<th>Name</th>
<th>Salary</th>
<th>Wallet</th>
</tr>
</thead>
<tbody>
<?php
$conn = mysqli_connect("bla bla bla");
$result = mysqli_query($conn, "SELECT * FROM darkrp_player inner join playerinformation on (darkrp_player.uid = playerinformation.uid) ORDER BY wallet DESC");
$rank = 1;
while ($row = mysqli_fetch_assoc($result)):
?>
<?php
$steamid2 = $row['steamID'];
$slice = substr($steamid2, strpos($steamid2, ":") + 1);
$n = substr($slice, 0, 1);
$x = substr($slice, strpos($slice, ":") + 1);
$steamid64 = 76561197960265728 + 2 * $x + $n;
$json = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=keykeykeykeykeyk&steamids='.$steamid64.'');
$parsed = json_decode($json);
?>
<tr id="rank<?php echo $rank++; ?>">
<td><?php echo $rank - 1; ?></td>
<td><?php foreach($parsed->response->players as $player){
echo "<img src='" . $player->avatarmedium . "'>";
} ?></td>
<td><?php foreach($parsed->response->players as $player){
echo "" . $player->personaname . "";
} ?></td>
<td><?php echo $row['salary']; ?></td>
<td><?php echo $row['wallet']; ?></td>
<?php endwhile; ?>
</tr>
</tbody>
</table>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.6.0/dt-1.13.1/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.6.0/dt-1.13.1/datatables.min.js"></script>
<script>
$(".table").DataTable();
</script>

Group by ( remarks ) Value in php mysql

Below is products table :
id | mid | wgh | remark| remkok |
1 3 1.5 r3ok 1
2 2 1.5 0
3 2 0.6 nice 0
4 1 1.2 okh 0
5 4 1.5 bye 0
6 4 2.4 okby 0
7 3 3.0 oknice 1
I want to display remark below tr of group by mid..like below
mid wgh
3 1.5
3.0
remarks : r3ok, oknice
4 1.5
2.4
remarks : bye, okby
2 1.5
0.6
remarks : , nice
1 1.2
remarks : okh
What I have tried as below :
$pid= null;
while($row = mysql_fetch_array($result))
{
$rowpkts = $row['mid'];
echo "<tr class=\"undercl\">";
if($rowpkts != $pid){
echo'<td align="center" valign="top">'.$row["mid"].'</td>';
}else{
echo'<td align="center" valign="top"></td>';
}
echo'<td align="center" valign="top">'.$row["wgh"].'</td>';
echo "</tr>";
// what i tried to build for remarks as below
$remsql = "SELECT mid as onu , GROUP_CONCAT(`remark` ORDER BY `id` ASC SEPARATOR ', ') AS plrmks
FROM products WHERE 1=1 GROUP BY `mid`";
$fetchremk = mysql_query($remsql);
$rowresults = mysql_fetch_array($fetchremk);
if($rowresults['onu'] == $pid ){
echo"<tr style='border-style:underline;'>";
echo'<td align="center" align="top">'.$rowresults["plrmks"].'</td>';
echo"</tr>";
}
}
$pid = $rowpkts;
}
But remarks is not coming proper below tr... it means its not display below mid=3 or mid=1.
Any other way,that would help me.
Add appropriate colspan as required and do not do center align.
Try below code
while($row = mysql_fetch_array($result))
{
$rowpkts = $row['mid'];
echo "<tr class=\"undercl\">";
if($rowpkts != $pid){
echo'<td align="center" valign="top">'.$row["mid"].'</td>';
}else{
echo'<td align="center" valign="top"></td>';
}
echo'<td align="center" valign="top">'.$row["wgh"].'</td>';
echo '</tr>';
$remsql = "SELECT mid as onu , GROUP_CONCAT(`remark` ORDER BY `id` ASC SEPARATOR ', ') AS plrmks
FROM products WHERE `remkok`= 1 GROUP BY `mid`";
$fetchremk = mysql_query($remsql);
$rowresults = mysql_fetch_array($fetchremk);
if($rowresults['onu'] == $pid ){
echo"<tr><td colspan ='?'> Remarks : ";
echo $rowresults["plrmks"];
echo "</td></tr>";
}
$pid = $rowpkts;
}

SQL calculate row number

I doing league table football and There is a profile of Team (Like : Team.php?team=XXX)
In this page I want to show, What position of TeamXXX in League Table
Page League Table
<?php
$number = 0;
$sql = "SELECT * FROM `leaguetable` WHERE `league` = 'leaguename' ORDER BY pts DESC";
$query = mysql_query($sql);
while($rs=mysql_fetch_assoc($query)){
$number++;
?>
<table>
<thead>
<tr>
<th>Position</th>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<td><?php echo $number; ?></td>
<td><?php echo $rs['team']; ?></td>
<td><?php echo $rs['pts']; ?></td>
</tbody>
</table>
<?php } ?>
Data in Table leaguetable
id team pts
In team.php I want to show position of TeamXXX
<?php
$getTeam = mysql_fetch_assoc(mysql_query("SELECT * FROM `leaguetable` WHERE `team`='"$_GET['team']"'");
?>
<table>
<thead>
<tr>
<th>Position</th>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<td>#########</td>
<td><? echo $getTeam['team']; ?></td>
<td><? echo $getTeam['pts']; ?></td>
</tbody>
</table>
How can I know what position of teamXXX in leaguetable?
Any help will be greatly appreciated. Thank you very much
query
select id, team, pts, rnk
from
(
select leag.id, leag.team, leag.pts,
#rnk := if(leag.pts = #lag, #rnk,
if(#lag := leag.pts, #rnk + 1, #rnk + 1)) as rnk
from leaguetable leag
cross join ( select #rnk := 0, #lag := null ) params
where league = 'FA Cup'
order by leag.pts desc
) rankings
where team = 'Chelsea'
;
example.php
<?php
/**
* Mysqli initial code
*
* User permissions of database
* Create, Alter and Index table, Create view, and Select, Insert, Update, Delete table data
*
* #package PhpFiddle
* #link http://phpfiddle.org
* #since 2012
*/
require_once "dBug!.php";
require "util/public_db_info.php";
$short_connect = new mysqli($host_name, $user_name, $pass_word, $database_name, $port);
if (mysqli_connect_errno())
{
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
/*
$sql = "create table leaguetable"
. "("
. " id integer primary key not null,"
. " team varchar(33) not null,"
. " pts integer not null default 0"
. ");";
$result = $short_connect->query($sql);
if(!$result)
{
die("Create table failed : " . mysqli_error($short_connect));
}
$sql = "insert into leaguetable"
. "( id, team, pts )"
. "values"
. "( 1, 'Liverpool', 22 ),"
. "( 2, 'Arsenal', 29 ),"
. "( 3, 'Chelsea', 23 ),"
. "( 4, 'Tottenham', 23)";
$result = $short_connect->query($sql);
if(!$result)
{
die("insert failed : " . mysqli_error($short_connect));
}
*/
//get all tables in the database
//$sql = "SHOW TABLES";
//get column information from a table in the database
//$sql="SELECT COLUMN_KEY, COLUMN_NAME, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_NAME = 'books'";
//SQL statement for a table in the database
$sql = "select id, team, pts, rnk "
. "from"
. "("
. "select leag.id, leag.team, leag.pts,"
. "#rnk := if(leag.pts = #lag, #rnk,"
. " if(#lag := leag.pts, #rnk + 1, #rnk + 1)) as rnk "
. "from leaguetable leag "
. "cross join ( select #rnk := 0, #lag := null ) params "
. " where league = 'FA Cup' "
. "order by leag.pts desc;"
. ") rankings "
. where team = 'Chelsea';";
//result is boolean for query other than SELECT, SHOW, DESCRIBE and EXPLAIN
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0))
{
echo "<table>" . "<thead>" . "<tr>" . "<th>Position</th>" . "<th>Team</th>" . "<th>Points</th>" . "</tr>" . "</thead>" . "<tbody>";
//convert query result into an associative array
echo "<tr><td>" . $row['rnk'] . "</td><td>" . $row['team'] . "</td><td>" . $row['pts'] . "</td></tr>";
echo "</tbody></table>";
}
else
{
die("select failed : " . mysqli_error($short_connect));
}
$short_connect->close();
?>
output
<table>
<thead>
<tr>
<th>Position</th>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>Chelsea</td>
<td>23</td>
</tr>
</tbody>
</table>
sqlfiddle
Hope this will help
$number = 0;
$points=0;
$sql = "SELECT * FROM `leaguetable` WHERE `league` = 'leaguename' ORDER BY pts DESC";
$query = mysql_query($sql);
while($rs=mysql_fetch_assoc($query)){
if($points!=$rs['pts'])
$number++;
if($rs['team']==$_GET['team']){
if($points==$rs['pts'])
$position=$number-1;
else
$position=$number;
}
$poins=$rs['pts'];
}
If you don't mind using two queries (I wouldn't mind it), it's pretty easy: Just count how many teams have more points, and add one (so that if three teams are tied in second position, they all get position 2).
$result = mysql_query("SELECT count(*)+1 AS POSTN FROM leaguetable WHERE
league = 'leaguename' AND pts > $points");
$row = mysql_fetch_assoc($result);
$position = $row["POSTN"];
Doing it in one query is a bit messier, since you need to embed this query in your original one:
"SELECT *, (SELECT count(*)+1 FROM leaguetable table2
WHERE league = 'leaguename' AND table2.pts > leaguetable.pts) AS POSTN
FROM leaguetable WHERE team = '$currentteam'"
But why are you using the mysql_* API for new code? Haven't you noticed all the dire warnings in pink boxes in the documentation? Do yourself a favor and switch to mysqli today, starting with this program.
Also: Never just inject $_GET[param] into your query string! You're giving yourself an SQL injection attack waiting to happen... and brittle, error-prone code until then.

How to sum each column in MySQL table with PHP

I want to display the total of each column inside the table. Here is my code.
$Tab_info['Width'] = "600" ;
$Col_det = array(
'Name' => array( 'Name',
'Aging Create Order ( <= 5 )',
'Aging Create Order ( > 5 )',
'Total'),
'Size' => array( '200' , '200' , '200' , '100' ),
'Type' => array('sortable-text fd-column-', 'sortable-numeric fd-column-','sortable-numeric fd-column-','sortable-numeric fd-column-'));
$Delim_String = '<table id="Summary" class="sortable-onload-0-normal rowstyle-alt no-arrow" style="width:'.$Tab_info['Width'].'px;background-color:#FFFFFF;">';
$Delim_String .= '<thead><tr>';
for ($Col_count = 0; $Col_count < sizeof($Col_det['Name']) ; $Col_count++) {
$Delim_String .= '<th style="-moz-user-select: none;" class="'.$Col_det['Type'][$Col_count].$Col_count.'" width="'.$Col_det['Size'][$Col_count].'">';
$Delim_String .= '<a title="Sort on '.$Col_det['Name'][$Col_count].'" href="#">'.$Col_det['Name'][$Col_count].'</a>';
$Delim_String .= '</th>';
}
$Delim_String .= '</tr>
</thead>
<tbody>
';
//===================Summary Aging Create Order End===========================
$vSQL = "SELECT u.Nama as Name,
SUM( CASE WHEN t.`AgingCreateOrder` <= 5 THEN 1 ELSE 0 END) 'Aging Less Than or Equal 5',
SUM( CASE WHEN t.`AgingCreateOrder` > 5 THEN 1 ELSE 0 END) 'Aging More Than 5',
COUNT(*) as Total
FROM `oct_usergroup` u
JOIN `oct_tickets` t
ON (t.`Creator_SubType`= u.`Id`)
WHERE
t.Date_Created >= (CURDATE() -INTERVAL 49 DAY)
AND u.Nama IS NOT NULL
AND t.AgingCreateOrder between '1' and '1999'
AND t.Status = 1
GROUP BY u.`Nama`";
$result = mysql_query($vSQL)or die($vSQL."<br/><br/>".mysql_error());
while($row = mysql_fetch_array ($result))
{
$Delim_String .= '
<tr>
<td>'.$row['Name'].'</td>
<td>'.$row['Aging Less Than or Equal 5'].'</td>
<td>'.$row['Aging More Than 5'].'</td>
<td>'.$row['Total'].'</td>
</tr>';
}
$Delim_String .= "</tbody></table>";
$table1 = $Delim_String;
unset($Delim_String);
//===================Summary Aging Update Address start===========================
$Tab_info['Width'] = "600" ;
$Col_det = array(
'Name' => array( 'Name',
'Aging Update Address ( <= 5 )',
'Aging Update Address ( > 5 )',
'Total'),
'Size' => array( '200' , '200' , '200' , '100' ),
'Type' => array('sortable-text fd-column-', 'sortable-numeric fd-column-','sortable-numeric fd-column-','sortable-numeric fd-column-')
);
$Delim_String = '<table id="Summary" class="sortable-onload-0-normal rowstyle-alt no-arrow" style="width:'.$Tab_info['Width'].'px;background-color:#FFFFFF;">
';
$Delim_String .= '<thead>
<tr>
';
for ($Col_count = 0; $Col_count < sizeof($Col_det['Name']) ; $Col_count++) {
$Delim_String .= '
<th style="-moz-user-select: none;" class="'.$Col_det['Type'][$Col_count].$Col_count.'" width="'.$Col_det['Size'][$Col_count].'">';
$Delim_String .= '<a title="Sort on '.$Col_det['Name'][$Col_count].'" href="#">'.$Col_det['Name'][$Col_count].'</a>';
$Delim_String .= '</th>
';
}
$Delim_String .= '</tr>
</thead>
<tbody>
';
I want it to show like this.
====================================================================
| Name | Aging Create Order <=5 | Aging Create Order >5 | Total |
---------------------------------------------------------------------
| Consumer | 159 | 80 | 239 |
---------------------------------------------------------------------
| CSO | 20 | 50 | 70 |
---------------------------------------------------------------------
| Total | 179 | 130 | 309 |
=====================================================================
The last row is the one to be added.
Try with this
$result = mysql_query($vSQL)or die($vSQL."<br/><br/>".mysql_error());
$gt_less = 0;
$gt_more = 0;
$gt_total = 0;
while($row = mysql_fetch_array ($result))
{
$gt_less += $row['Aging Less Than or Equal 5'];
$gt_more += $row['Aging More Than 5'];
$gt_total += $row['Total'];
$Delim_String .= '
<tr>
<td>'.$row['Name'].'</td>
<td>'.$row['Aging Less Than or Equal 5'].'</td>
<td>'.$row['Aging More Than 5'].'</td>
<td>'.$row['Total'].'</td>
</tr>';
}
$Delim_String .= '
<tr>
<td>Grand Total</td>
<td>'.$gt_less.'</td>
<td>'.$gt_more.'</td>
<td>'.$gt_total.'</td>
</tr>';
$Delim_String .= "</tbody></table>";

inside while loop data not displaying in php

Hi in the below i want to show Consultation Charges values for that i took the td.But in that td not displying anything even td also not showing.
After executing this query i want to find the no. of rows based on the rows i want to display the data.
My expected output:
Bill Particular Bill Sub Particular Doctor Date Dis. Amt.
Consultation Charges:
all the values based on no of rows.
php
<table width="100%">
<th>Bill Particular</th>
<th>Bill Sub Particular</th>
<th>Doctor</th>
<th>Date</th>
<th>Dis. Amt.</th>
<th>Charge</th>
<th>No. of Times</th>
<th>Amount</th>
</table>
<tr><th colspan=2>Consultation Charges:</th>
<?php
$div_options = array();
$sql = "SELECT ibp.ipd_bp_id, ibp.bp_id, bp.bp_name, ibp.bsp_id, bsp.bsp_name, ibp.doctor_id, ab.employee_name doctor, ibp.date date, ibp.amount charge, ibp.discount_amount discount, ibp.no_of_time, (ibp.no_of_time * ibp.amount) total_amount
FROM bill_particular_master bp
INNER JOIN ipd_bill_particular ibp ON ibp.bp_id = bp.bp_id
LEFT OUTER JOIN bill_sub_particular bsp ON bsp.bsp_id = ibp.bsp_id
LEFT OUTER JOIN address_book ab ON ab.employee_id = ibp.doctor_id
WHERE ibp.ipd_reg_no = '$ipd_no'
AND bsp.consultant =1
AND bsp.package = 0
AND bsp.admission = 0
AND bp.bp_name != 'Scan Charges'
AND bp.bp_name !='Procedure'";
$sth = $dbh->query($sql);
//$row=$dbh->fetch();
$i=1;
while($row=$sth->fetch(PDO::FETCH_ASSOC)){
$sub_arr['bp_name'] = $row['bp_name'];
$sub_arr['bsp_name'] = $row['bsp_name'];
echo "<tr>
<td>Here is the text - " . $sub_arr['bp_name'] . "</td>
<td>The ID of the text is - " .$sub_arr['bsp_name'] . "</td>";
if($i !== 0) {
echo "<td>The ID of the previous entry is - " .$sub_arr['bp_name'] . "</td>";
}
else {
echo "<td> </td>";
}
echo "</tr>";
$i = $row['bp_name'];
}
?>
</tr>
echo "<td>The ID of the previous entry is - " . $row['bp_name'] . "</td>";
You have there variable thats not even defined in your code.

Categories