I have 3 tables i want to display the 3 table data in single table based on primary key, foreign key the result came perfectly! But i need to calculate rank based on the total marks from my second table.
result screenshot:
Please anyone tell me the query to calculate rank
I used the following mysql query
if(isset($_POST['submit']))
{
$result = mysqli_query($con,"
SELECT s.student_name
, s.contact_number
, m.total
, m.rank
, p.father_name
FROM student_details s
JOIN mark m
ON s.student_id = m.student_id
JOIN parents_details p
ON p.student_id = s.student_id
WHERE s.student_name = '".$_POST['student_name']."'
");
echo "<table border='1' align='center' cellpadding='15' bgcolor='#FFFFFF'>
<tr>
<th>NAME</th>
<th>CONTACT NUMBER</th>
<th>TOTAL MARK</th>
<th>RANK</th>
<th>FATHER NAME</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['student_name'] . "</td>";
echo "<td>" . $row['contact_number'] . "</td>";
echo "<td>" . $row['total'] . "</td>";
echo "<td>" . $row['rank'] . "</td>";
echo "<td>" . $row['father_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
}?>
SELECT * FROM
(
SELECT #rank := #rank+1 finalrank,ZZ.* FROM
(
SELECT student_details.student_name,
student_details.contact_number, mark.total,
mark.rank, parents_details.father_name
FROM student_details
INNER JOIN mark ON student_details.student_id=mark.student_id
INNER JOIN parents_details ON parents_details.student_id=student_details.student_id ,(SELECT #rank:=0)z
ORDER BY mark.total desc
)ZZ
)ZZZ
WHERE ZZZ.student_name = '".$_POST['student_name']."'
Just try above query.
Here I had used SELECT #rank:=0 and #rank := #rank+1.
Related
I am currently stuck attempting to understand how I loop results inside an existing loop using SQL results from joined tables.
Firstly, here is my current code:
<?php
include('OrderCore/connect-db.php');
$POIds = array();
if ($result = $mysqli->query("SELECT ProductionOrderID FROM ProductionOrder" ) ) {
while ($row = $result->fetch_object()) {
$POIds[] = $row->ProductionOrderID;
}
}
foreach ( $POIds as $index => $OrderId ) {
if ( $result = $mysqli->query("
SELECT *
FROM ProductionOrder AS p
LEFT JOIN ProductionOrderStatus AS s ON ( p.ProductionOrderID = s.ProductionOrderStatusID )
LEFT JOIN NotGood AS n ON ( p.ProductionOrderID = n.NGID )
LEFT JOIN BatchOrder AS b ON ( p.ProductionOrderID = b.ProductionOrderID)
LEFT JOIN Brand AS bd ON ( p.ProductionOrderID = bd.BrandID )
LEFT JOIN CustomerOrder AS co ON ( p.ProductionOrderID = co.COID )
LEFT JOIN Customer AS c ON ( p.ProductionOrderID = c.CustomerID )
LEFT JOIN CustomerOrderStatus AS cos ON ( p.ProductionOrderID = cos.COStatusID )
WHERE p.ProductionOrderID='$OrderId'") ) {
while( $row = $result->fetch_object() ) {
print "<h1>Order: $OrderId</h1>";
print "<table class='table table-striped'>";
print "<tr> <th>PO ID</th> <th>PO #</th> <th>Order Quantity</th> <th>Balance Left</th> <th>Production Date</th> <th>Production Order Status</th> <th>Not Good ID</th> </tr>";
print "<td>" . $row->ProductionOrderID . "</td>";
print "<td>" . $row->PONum . "</td>";
print "<td>" . $row->OrderQTY . "</td>";
print "<td>" . $row->BalLeftNum . "</td>";
print "<td>" . $row->ProductionDate . "</td>";
print "<td>" . $row->ProductionOrderStatusID . "</td>";
print "<td>" . $row->NGID . "</td>";
print "</tr>";
print "</table>";
//BatchOrder
print "<table class='table table-striped'>";
print "<tr> <th>Batch ID</th> <th>Brand Name</th> <th>Batch Quantity</th> <th>Availability Date</th> <th>Remaining Balance</th> <th>Production Order ID</th> </tr>";
print "<td>" . $row->BatchID . "</td>";
print "<td>" . $row->BrandID . "</td>";
print "<td>" . $row->BatchQTY . "</td>";
print "<td>" . $row->AvailDate . "</td>";
print "<td>" . $row->RemainBal . "</td>";
print "<td>" . $row->ProductionOrderID . "</td>";
print "</tr>";
print "</table>";
//CustomerOrder
print "<table class='table table-striped'>";
print "<tr> <th>Customer ID</th> <th>Customer Name</th> <th>Invoice Quantity</th> <th>Invoice #</th> <th>Shipping Date</th> <th>Batch ID</th> <th>CO Status</th> </tr>";
print "<td>" . $row->COID . "</td>";
print "<td>" . $row->CustomerID . "</td>";
print "<td>" . $row->InvoiceQTY . "</td>";
print "<td>" . $row->InvoiceNum . "</td>";
print "<td>" . $row->ShipDate . "</td>";
print "<td>" . $row->BatchID . "</td>";
print "<td>" . $row->COStatusID . "</td>";
print "</tr>";
print "</table>";
}
}
else
{
print "No results to display!";
}
}
$mysqli->close();
?>
This code currently produces this result: https://i.imgur.com/y7uh6nk.png.
This is almost the correct, intended behaviour... Each ProductionOrderID should generate a new table which has 2 child tables: BatchOrder and CustomerOrder. But it's currently only showing 1 result for each child table.
So to clarify, there can be any number of ProductionOrders created by the user (hence the foreach looping through the array). Each ProductionOrder can contain: Zero, One or Many BatchOrders and each BatchOrder can contain: Zero, One or Many CustomerOrders.
The current issue:
As per the screenshot link just above, it is only displaying 1 BatchOrder and 1 CustomerOrder per ProductionOrder. My sample data contains multiple Batch Orders for ProductionOrderID=1 but they aren't displaying.
I am not sure if the issue is partly PHP and partly SQL related. I am new to both languages but I suspect LEFT JOIN is incorrect. However, it was the only method (currently) to display each ProductionOrder correctly with a BO and CO each... Just not all of them. I also suspect I need to execute another loop inside my existing while loop but I'm not sure on the correct approach as my current attempts have all been unsuccessful.
Detailed Information
Here is a copy of my database SQL with sample data: https://pastebin.com/A3rt8kX4
Also my ERD to show intended behaviour: https://i.imgur.com/idVR5ev.png
Any help to not just help solve this current issue but to help me understand why it's wrong is absolutely appreciated.
EDIT: 1
I have fixed the keys joined in my SELECT statement but now only see one PO:
https://i.imgur.com/doRmS0c.png
SELECT *
FROM ProductionOrder AS p
INNER JOIN ProductionOrderStatus AS s ON ( p.ProductionOrderID = s.ProductionOrderID )
INNER JOIN NotGood AS n ON ( p.ProductionOrderID = n.ProductionOrderID )
INNER JOIN BatchOrder AS b ON ( p.ProductionOrderID = b.ProductionOrderID )
INNER JOIN Brand AS bd ON ( b.BatchID = bd.BatchID )
INNER JOIN CustomerOrder AS co ON ( b.BatchID = co.BatchID )
INNER JOIN Customer AS c ON ( co.COID = c.COID )
INNER JOIN CustomerOrderStatus AS cos ON ( co.COID = cos.COID )
WHERE p.ProductionOrderID='$OrderId'") ) {
You need to join the primary key to the corresponding foreign key, for example:
LEFT JOIN ProductionOrderStatus AS s ON ( p.ProductionOrderID = s.ProductionOrderStatusID )
should be
LEFT JOIN ProductionOrderStatus AS s ON ( p.ProductionOrderID = s.ProductionOrderID )
You have the same issue in most of your joins.
I have a main php page where the user inputs a date range to view a table. I am using a jquery datepicker and am passing the values from the datepicker to another php page via ajax where my SELECT statement occurs. The values pass successfully and I can echo them back to the original page in the "yyyy-mm-dd" format (which is what I want). Then, I need to run a SELECT statement pulling only rows out where the orderdate is between the datepicker values picked by the user. When I run my query without the WHERE clause, the query is successful, and my table displays data. When I had the Where clause, the table headers displayed, but the data wouldn't. How do I get the variables to work with the query without the risk of SQLi?
Here is my code pulling datepicker values from ajax (and an attempt to convert the string to a date format - I am new to this and wasn't sure if that was the problem):
//Get date range.
$revenuefromajax=$_POST['revenuefromtext'];
$revenuetoajax=$_POST['revenuetotext'];
$revenuefromstring = strtotime($revenuefromajax);
$revenuetostring = strtotime($revenuetoajax);
$revenuefrom=date("Y-m-d", $revenuefromstring);
$revenueto=date("Y-m-d", $revenuetostring);
echo $revenuefrom;
echo $revenueto;
MySQL Query:
$sql = "SELECT invoices.id, invoices.orderdate, invoices.stagestatus, FORMAT(TRIM(LEADING '$' FROM invoices.totalprice), 2) AS totalprice, clients.company, lineitems.invoiceid, FORMAT((lineitems.width * lineitems.height) /144, 2 ) AS sqft, lineitems.quantity AS qty, FORMAT((invoices.totalprice / ((lineitems.width * lineitems.height) /144)), 2) as avgsqftrevenue, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice) / lineitems.quantity), 2) AS avgunitrevenue
FROM clients
INNER JOIN invoices ON clients.id = invoices.clientid
INNER JOIN lineitems ON invoices.id = lineitems.invoiceid
WHERE invoices.ordedate BETWEEN ('".$revenuefrom."') AND ('".$revenueto."')
ORDER BY invoices.id DESC
LIMIT 10";
$result = $conn->query($sql);
echo "<table id='revenueReportA' align='center' class='report_DT'>
<tr>
<th>Customer</th>
<th>SG</th>
<th>Revenue</th>
<th>SQ FT</th>
<th>AVG Revenue Per SQ FT</th>
<th>Number of Units</th>
<th>AVG Revenue Per Unit</th>
</tr>";
if ($result = $conn->query($sql)) {
// fetch associative array
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" ."$". $row['totalprice'] . "</td>";
echo "<td>" . $row['sqft'] ." ". "ft<sup>2</sup>". "</td>";
echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>";
echo "<td>" . $row['qty'] . "</td>";
echo "<td>" ."$". $row['avgunitrevenue'] . "</td>";
echo "</tr>";
}
echo "</table>";
I would like to ask how to show one row only in same id, in below example, I just want to show the highest score result in the table.
Here is my code
$query = "SELECT * FROM memberdata ORDER BY score DESC";
echo "<table border=1>
<tr>
<th> id </th>
<th> score </th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['score'] . "</td>";
echo "</tr>";
}
echo "</table>";
And the Output is
id score
1 5000
1 4000
1 3000
1 500
2 3000
2 1000
Use Group by
SELECT id, MAX(score) AS score FROM memberdata GROUP BY id
Try this:
SELECT id, MAX(score) AS score FROM memberdata GROUP BY id
or this:
SELECT * FROM memberdata ORDER BY score DESC LIMIT 1
You need to iterate to find the maxrow first.
$query = "SELECT * FROM memberdata ORDER BY score DESC";
echo "<table border=1>
<tr>
<th> id </th>
<th> score </th>
</tr>";
$maxrow = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)) {
if ($maxrow['score'] > row['score']) maxrow = row;
}
echo "<tr>";
echo "<td>" . $maxrow['id'] . "</td>";
echo "<td>" . $maxrow['score'] . "</td>";
echo "</tr>";
echo "</table>";
I am working on a formula where I am adding multiple values in a row and column depending on the values of other cells. For example I have the following working code:
$result = mysql_query("SELECT School,SUM(Wins + Losses) as total FROM tennis GROUP BY School");
echo "<table border='1'>
<tr>
<th>School</th>
<th>Score</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['School'] . "</td>";
echo "<td>" . $row['total'] . "</td>";
echo "</tr>";
}
However I want to add more columns that are also sums of other rows/columns and don't know how to do this while still keeping everything Grouped by the column 'School'. What I essentially want is the following, but the code is incorrect:
$result = mysql_query("SELECT School,SUM(Wins + Losses) as 1sttotal FROM tennis WHERE Event='1st Singles', SUM(Wins + Losses) as 2ndtotal FROM tennis WHERE Event='2nd Singles' GROUP BY School");
echo "<table border='1'>
<tr>
<th>School</th>
<th>1st Singles</th>
<th>2nd Singles</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['School'] . "</td>";
echo "<td>" . $row['1sttotal'] . "</td>";
echo "<td>" . $row['2ndtotal'] . "</td>";
echo "</tr>";
}
I'm new to PHP so I'm not sure the correct/optimal way to go about setting this up. Thanks
this is the query you should use to get the 2 totals:
SELECT
School,
SUM(IF(Event='1st Singles', Wins + Losses, 0)) as 1sttotal,
SUM(IF(Event='2nd Singles', Wins + Losses, 0)) as 2ndtotal
FROM tennis
GROUP BY School;
See how it adds according to the event columns? The trick is to pass a WHERE filter within the SELECT clause through conditional execution (IF)
Other possibility using CASE WHEN:
SELECT
School,
SUM(
CASE
WHEN Event='1st Singles' THEN Wins + Losses
ELSE 0
END
) as 1sttotal,
SUM(
CASE
WHEN Event='2nd Singles' THEN Wins + Losses
ELSE 0
END
) as 2ndtotal
FROM tennis
GROUP BY School;
I have two tables.
visitors_details, with id,scanner_id,time columns
and visitors_info with scanner_id, name,surname columns
I want to get back
id,name,surname,time in a table
i have written this but is not working
$result = mysql_query("SELECT visitors_details.id AS id,
visitors_info.name AS name, visitors_info.surname AS surname, visitors_details.time
AS time FROM visitors_details AS d LEFT JOIN visitors_info AS i ON
d.scanner_id=i.scanner_id ");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>surname</th>
<th>Time</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
echo "</tr>";
}
echo "</table>";
any ideas??
Its better to enable some debugging for your code like this:
<?php
error_reporting(E_ALL);
$sql = "
SELECT d.id AS id, i.name AS name, i.surname AS surname, d.time AS time
FROM visitors_details AS d
LEFT JOIN visitors_info AS i ON d.scanner_id=i.scanner_id
";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
try this query
$result = mysql_query("SELECT d.id , i.name , i.surname , d.time
FROM visitors_details AS d LEFT JOIN visitors_info AS i
ON d.scanner_id=i.scanner_id ");
Add this to catch errors. saves a lot of time:
if(!$result) {
echo mysql_error();
}