PHP MySQL Queries - Addition - php

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;

Related

How to calculate rank based on total marks

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.

include php date variable in MySQL SELECT query

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>";

How to display records in table with top 10 enteries with specific colour

I an trying to display records in table with top 10 enteries with specific color
My Query just for Ref.
$sqlsum=mysql_query("SELECT `userid`, SUM(`points`) as `total` FROM
`tablename` GROUP BY `userid` ORDER BY total DESC LIMIT 10");
This code below displays a simple table, I need to display table With TOP 10 entries be different in colour[blue].. rest remains the same [white background].
i.e Top 10 can be in blue color, and rest in white color.
Below is the code I am using to display records.
<?php
while($row = mysql_fetch_array($sqlsum))
{
echo "<tr> ";
echo "<td>" .$row[userid] . "</td>";
echo "<td>" .$row[total] . "</td>";
}
echo "</tr> " ;
?>
I have this table structure as sample. That I want to use, with this code. The table need to be the same , but i am not to find the logic , how to build the table
with this structure
<table>
<thead><tr><td colspan="2"><center>Prizes</center></td></tr><tr>
<th>Position</center></th><th><center>Prize</center></th></tr></thead>
<tbody><tr><td>1st</td><td>0.0$</td></tr>
<tr class="alt"><td>2nd</td><td>0.0$</td></tr>
<tr><td>3rd</td><td>0.0$</td></tr>
<tr class="alt"><td>4th</td><td>0.0$</td></tr>
<tr><td>5th</td><td>0.0$</td></tr>
</tbody>
</table>
Remove Limit 10 For Fetch All Data:
$sqlsum=mysql_query("SELECT `userid`, SUM(`points`) as `total` FROM
`tablename` GROUP BY `userid` ORDER BY total DESC");
php:
<?php
$i=1;
while($row = mysql_fetch_array($sqlsum))
{
echo "<tr ".(($i <= 10) ? "bgcolor='blue'" : '')'."> ";
// Apply attrinute bgcolor for backgroung color
echo "<td>" .$row[userid] . "</td>";
echo "<td>" .$row[total] . "</td>";
echo "</tr>";
$i++;
}
?>
Set an indicator variable to point it.
<?php
$rowNumber = 0;
while($row = mysql_fetch_array($sqlsum))
{
if ($rowNumber < 10)
{
echo "<tr class=\"alt\"> ";
}
else
{
echo "<tr> ";
}
echo "<td>" .$row[userid] . "</td>";
echo "<td>" .$row[total] . "</td>";
echo "</tr> " ;
$rowNumber++;
}
?>

How to calculate kills/deaths ratio in a computer game?

I need my computer game to take all kills and deaths from a user's total and then make it so the kills are divided by the deaths, then that total is put at the end. This ratio is known as their kill-death ratio, or "KDR".
<?php
// Create connection
$con=mysqli_connect("ipaddress","user","password","minecraft");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT *, `kills`/`deaths` as `KDR` FROM war_kills ``ORDER BY kills DESC");
echo "<table border='1'>
<tr>
<th>Player</th>
<th>Kills</th>
<th>Deaths</th>
<th>KDR</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['player'] . "</td>";
echo "<td>" . $row['kills'] . "</td>";
echo "<td>" . $row['deaths'] . "</td>";
echo "<td>" . $row['KDR'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
We have this up so far: http://gexgaming.com/warstats/index.php
Change the query from
SELECT player, kills, deaths, KDR FROM war_kills ORDER BY kills DESC`
to
SELECT player, kills, deaths, kills / deaths as KDR FROM war_kills ORDER BY kills DESC`
Either modify the SQL query as suggested or do it within the PHP loop:
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['player'] . "</td>";
echo "<td>" . $row['kills'] . "</td>";
echo "<td>" . $row['deaths'] . "</td>";
echo "<td>" . ($row['kills'] / $row['deaths']) . "</td>"; // <--- this one
echo "</tr>";
}
It looks like you need to group your results based on the player name. Also, you need to account for when deaths = 0. Try changing your query to -
SELECT
player,
SUM(kills) as kills,
SUM(deaths) as deaths,
CASE WHEN SUM(deaths) = 0 THEN SUM(kills)
ELSE SUM(kills)/SUM(deaths)
END as `KDR`
FROM war_kills
GROUP BY player
ORDER BY kills DESC
The other answers I read don't account for the fact that someone might have zero deaths. If they do, you'll get a divide by zero error.
inside your while loop,
if ($row['deaths'] == 0)
$kdr = '-';
else
$kdr = $row['kills']/$row['deaths'];
then change $row['KDR'] to $kdr

PHP MySQL - Multiple Select Queries returned in while loop

I have the following code which works fine however historically and again now I want to (if possible) add a third select statement to collect further information and return it in my while loop i.e. as $row2.
Is there any way I can do this or will I have to rehash my code completely to make it work?
Any help or guidance will be gratefully received. Current code is as below:
mysql_select_db("jbsrint", $con);
$result = mysql_query("SELECT *, DATE_FORMAT(Date_Registered, '%d-%m-%Y') AS Date_Registered, DATE_FORMAT(Date_Last_MOT, '%d-%m-%Y') AS Date_Last_MOT, DATE_FORMAT(Date_Last_Tax, '%d-%m-%Y') AS Date_Last_Tax FROM Veh_List ORDER BY ID DESC");
$DUE_DATES = mysql_query("SELECT *, DATE_FORMAT(MOT_DUE_DATE, '%d-%m-%Y') AS MOT_DUE_DATE, DATE_FORMAT(Date_Tax_Due, '%d-%m-%Y') AS Date_Tax_Due FROM due_dates ORDER BY ID DESC");
echo "<table border='1'>
<tr>
<th>Vehicle Reg</th>
<th>Vehicle Make</th>
<th>Vehicle Model</th>
<th>Vehicle Colour</th>
<th>Date Registered</th>
<th>Date Of Last MOT</th>
<th>MOT Due</th>
<th>Date Of Last Tax</th>
<th>Tax Due</th>
<th>Vehicle Driver</th>
<th>Vehicle Driver Tel</th>
</tr>";
while($row = mysql_fetch_array($result) and $row1 = mysql_fetch_array($DUE_DATES))
{
echo "<tr>";
echo "<td class=\"td1\">" . $row['Vehicle_Reg'] . "</td>";
echo "<td >" . $row['Vehicle_Make'] . "</td>";
echo "<td class=\"td1\">" . $row['Vehicle_Model'] . "</td>";
echo "<td>" . $row['Vehicle_Colour'] . "</td>";
echo "<td class=\"td1\">" . $row['Date_Registered'] . "</td>";
echo "<td>" . $row['Date_Last_MOT'] . "</td>";
echo "<td class=\"td1\">" . $row1['MOT_DUE_DATE'] . "</td>";
echo "<td>" . $row['Date_Last_Tax'] . "</td>";
echo "<td class=\"td1\">" . $row1['Date_Tax_Due'] . "</td>";
echo "<td>" . $row['Vehicle_Driver'] . "</td>";
echo "<td class=\"td1\">" . $row['Vehicle_Driver_Tel'] . "</td>";
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?>
You should not use a separate query for each table. Instead you should use JOIN to retrieve related data from multiple tables in a single query:
SELECT
veh_List.col1,
veh_List.col2,
due_dates.col3,
...etc...
FROM veh_List
JOIN due_dates ON veh_List.id = due_dates.id
-- add more joins here if you need data from more tables
ORDER BY veh_List.id DESC
You should learn about the JOIN keyword and the various possibilities this provides, including understanding the difference between INNER JOIN and OUTER JOIN.
What is the difference between "INNER JOIN" and "OUTER JOIN"?
I believe you can simply add another statement and combine it in the same fashion as you had now but my suggestion is to use the opportunity that you are modifying the code and merge the SQL queries into one.
Also, looking at your database design - is there one-to-one relation between the due dates and registered cars? If so, why not merge the two tables together? (Of course, I can only see the columns you are using in your select queries).
Furthermore, it seems a bit dangerous to rely on the ordering to match up the records - what if one row from due dates is removed?

Categories