Display percentage from two sql columns - php

This is a small section of code i've been working with.
<?php
$rank = 0;
$rank = 0;
$sql = mysql_query("SELECT m.memberID, username,email,target,type, ifnull(t.total,0) as total, ifnull(m.total,0) as totalp FROM `members` as m
left join (
select s.memberID, sum(amount) total from sponsors as s group by s.memberID
) t on t.memberid = m.memberid
left join (
select s.memberID, sum(amount) total from sponsors as s group by s.memberID
) p on p.memberid = m.memberid Where type= 'business'
ORDER BY t.total DESC, p.total DESC, username ASC");
while($row = mysql_fetch_object($sql))
{
echo "<tr>";
$rank = $rank + 1;
echo "<td><center>$rank</center></td>";
echo "<td>$row->username</td>";
echo "<td>$row->total</td>";
echo "<td>$row->target</td>";
echo "<td>$row->here i want percentage</td>";
echo "</tr>";
}
?>
What I would like to do is display the percentage of total/target in the final column of my table. Not sure what the best way to do this is and would be keen to hear some ideas for this.
I did try doing it just as total/target in the echo but thinking it probably needs to be evaluated earlier as a variable or something? Whatever i tried didn't work anyway...
Looked at this but not sure how to implement it in my scenario - MSSQL display percentage calculated from two columns

Try this,
<?php
$rank = 0;
$rank = 0;
$sql = mysql_query("SELECT m.memberID, username,email,target,type, ifnull(t.total,0) as total, ifnull(m.total,0) as totalp, (ifnull(t.total,0)/target)*100 as present FROM `members` as m
left join (
select s.memberID, sum(amount) total from sponsors as s group by s.memberID
) t on t.memberid = m.memberid
left join (
select s.memberID, sum(amount) total from sponsors as s group by s.memberID
) p on p.memberid = m.memberid Where type= 'business'
ORDER BY t.total DESC, p.total DESC, username ASC");
while($row = mysql_fetch_object($sql))
{
echo "<tr>";
$rank = $rank + 1;
echo "<td><center>$rank</center></td>";
echo "<td>$row->username</td>";
echo "<td>$row->total</td>";
echo "<td>$row->target</td>";
echo "<td>$row->present</td>";
echo "</tr>";
}
?>

Here is logic
((cast("A/B" as float)/"C") * 100.00) AS "D%"
all value must be integer and when you are dividing them it must be convert as a float so calculation goes correctly.
Hope it will work for you.

Related

Calculate SUM in PHP

<?php
$today=date('Y-m-d');
$sorgu = mysqli_query($conn, "SELECT * FROM urun");
while ($sira = mysqli_fetch_array($sorgu)) {
$urun = $sira['urun'];
$query = mysqli_query($conn, "SELECT product_name, birim, SUM(quantity) FROM
product WHERE product_name = '$urun' AND quantity != '0' AND quantity > '0'
AND grup!='uygulama' AND skt > '$today' GROUP BY product_name, birim ");
while ($row = mysqli_fetch_array($query)){
if ($row['2'] <= $sira['minstok']) {
echo count($row['0']);
} } } ?>
This code belongs to a table which has a notification system. I want the notification part increase when the line number increases in that table but it turns 11111111... , So how can I make the code give me sum?
Incidentally, everything up to while ($row... can be rewritten as follows:
SELECT p.product_name
, p.birim
, SUM(p.quantity) total
FROM urun u
JOIN product p
ON p.product_name = u.urun
AND p.quantity > 0
AND p.grup != 'uygulama'
AND p.skt > CURDATE()
GROUP
BY p.product_name
, p.birim;

Selecting rows from multiple tables

I would like to know what the fastest way is to make the following SQL call using PHP. I am using procedural mySQLi.
$dcount = "SELECT max(id) FROM deposits";
$result = mysqli_query($conn,$dcount);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$count = $row["max(id)"];
echo $count;
echo ",";
}
} else {
echo '0';
}
//second query
$ucount = "SELECT max(int) FROM anothertable";
$result2 = mysqli_query($conn,$ucount);
if (mysqli_num_rows($result2) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$count = $row["max(int)"];
echo $count;
echo ",";
}
} else {
echo '0';
}
Is there a way to make the execution faster than like this, maybe to echo the results from both queries after the first if statement?
It just seems rather long to me.
Thanks in advance.
SELECT max(id) as max_id, (SELECT max(int) as max_int FROM anothertable) as max_int
FROM deposits
Not tested, but something like it should work
$dcount = "
SELECT max(id) as max,'deposit' as table_name FROM deposits
UNION
SELECT max(id) as max,'another' as table_name FROM anothertable
";
$result = mysqli_query($conn,$dcount);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo $row["table_name"].":".$row["max"]."\n";
}
} else {
echo '0';
}
SELECT d.max(id) as d_max_id, a.max(int) as a_max_int FROM deposits as d JOIN anothertable as a ON d.id = a.id;
is what you need for multiple tables
$row['d_max_id']
will give you deposits.max(id) now
You have to edit the d.id = a.id accordingly to what you want the two tables to match on
If you cant join try this:
SELECT max(id) as max_id, (SELECT max(int) FROM anothertable) as max_int FROM deposits;
SELECT max(id) as max_id, max(int) as max_int FROM deposits ,anothertable

complex mysql query need result sorted

I have 3 mysql tables. I want to display leaderboard for team in descending order of d_money for particular day (like day 1, day 2, day 3.)
user(u_id(p),name)
team(t_id(p),u_id(f),t_name,t_money,days_money) and
history(t_id(f),day,d_money).
First i collected all t_id's in $tid_arr. Then for each t_id, i wrote query to get t_name and its days money.(for particular day. Here - day 1). It displays the result. But i want the result sorted (descending order of d_money). But i couldn't find the soultion.
$query = $con->prepare("SELECT t_id FROM team");
$query->execute();
$tid_arr = $query->fetchAll();
echo "<table border='1'>";
foreach($tid_arr as $tid)
{
$que = $con->prepare("SELECT d_money, t_name FROM team, history WHERE history.t_id=$tid['t_id'] AND team.t_id=history.t_id` AND history.day='1'");
$que->execute();
while($info = $que->fetch(PDO::FETCH_NUM))
{
echo "<tr>";
echo "<td>".$info[0]."</td>";
echo "<td>".$info[1]."</td>";
echo "</tr>";
}
}
echo "</table>";
If you want to order by d_money then t_id, you can use the following query. The 1st query is unnecessary and should be removed.
SELECT d_money, t_name FROM team a
LEFT JOIN history b ON a.t_id=b.t_id
WHERE history.day='1'
ORDER BY d_money DESC, t_id DESC
p.s. user table is not used ?
Add a Join and Order By clause to your SQL statement to be
echo "<table border='1'>";
$que = $con->prepare("SELECT T.t_id, H.d_money, T.t_name
FROM team T INNER JOIN history H ON T.t_id=H.t_id
WHERE H.day='1'
ORDER BY d_money DESC");
$que->execute();
while ($info = $que->fetch(PDO::FETCH_NUM)) {
echo "<tr>";
echo "<td>".$info[0]."</td>";
echo "<td>".$info[1]."</td>";
echo "</tr>";
}
echo "</table>";

How can i remove duplicate values from an Echoed table?

I have managed to create a JOIN query for three tables and can successfully echo out the results in a echoed table, here is my code:
<?php
$sql="SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
ORDER BY product_name DESC";
$result = mysql_query($sql);
if (!$result)
{
echo "An error occurred ".mysql_error();
exit;
}
echo "<table border=1>\n<tr><th></th><th bgcolor=\"#DFE8EC\">Name</th><th>Flavors & Size</th><th bgcolor=\"#DFE8EC\">Price</th><th>Price Difference</th><th bgcolor=\"#DFE8EC\"></th></tr>\n";
while ($line = mysql_fetch_array($result)) {
$name = $line["product_name"];
$price = $line["product_price"];
$options=$line["Options_name"];
$difference=$line["Price_diff"];
echo "<tr><td></td><td bgcolor=\"#DFE8EC\">$name</td><td>$options</td> <td bgcolor=\"#DFE8EC\">£$price</td><td>£$difference</td><td bgcolor=\"#DFE8EC\"></td></tr>\n";
}
echo "</table>\n";
?>
My table works but it shows duplicate entries for product_name and I do not know how to remove them.
You have to use a GROUP BY clause in your query like this:
$sql = "SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
GROUP BY product_name
ORDER BY product_name DESC";

Checking a value isn't in another table in a query

I've looked around and I can't seem to find an answer to the following:
All I want to do is run an SQL select statement, to show the user something providing the invoice number (unique ID in this case) isn't showing in another table on the same database, at the moment the code is as follows:
$query = mysql_query("SELECT `ordate`, `invno` FROM `armast09` WHERE cshipno = '$username' AND `ordate` > DATE_SUB(CURDATE(), INTERVAL 4 DAY)") or die(header("location:index.php?e=4"));
$numrows = mysql_num_rows($query);
$date = date('o-n-d');
include 'indexfiles/top.php';
echo "The following deliveries are available for viewing / dispute:";
echo "<br />";
echo "<br />";
echo "<center>";
echo "<table>";
if($numrows != 0) {
while ($info = mysql_fetch_array($query)) {
echo "<tr>";
echo "<form action = \"deliverydispute.php?invno=".$info['invno']."\" method=\"POST\ onsubmit=\"return confirm('Are you sure you are ready to dispute? You can't go back after this.');\">";
echo "<td><b>Invoice Number: </b>".$info['invno']."</td>";
echo "<td><b>Order Date: </b>".$info['ordate']."</td>";
echo "<td>Dispute</td>";
echo "</form>";
echo "</tr>";
}
} else {
echo ("<font color=\"red\" face=\"arial\" size=\"2\"><small>No orders are currently available for viewing.</small></font>");
}
echo "</table>";
You can use the NOT IN predicate:
SELECT ordate, invno
FROM armast09
WHERE cshipno = '$username'
AND ordate > DATE_SUB(CURDATE(), INTERVAL 4 DAY)
AND invno NOT IN(SELECT invno FROM Anothertable WHERE invno IS NOT NULL);
Or LEFT JOIN:
SELECT a.ordate, a.invno
FROM armast09 a
LEFT JOIN anothertable a2 ON a.invno = a2.invno
WHERE a.cshipno = '$username'
AND a.ordate > DATE_SUB(CURDATE(), INTERVAL 4 DAY)
AND a.invno IS NULL;
You can do this easiy with the following:
SELECT X FROM TABLEA LEFT JOIN TABLEB ON TABLEA.ID = TABLEB.ID WHERE TABLEB.ID is null
That should do it!

Categories