include php date variable in MySQL SELECT query - php

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

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.

Conditional WHERE clause in SELECT using if statements and php variable

I'm trying to build a table that is conditionally organized based off user input. I need my WHERE and GROUP BY clauses to change based off user input values (from radio selects sent to php through ajax - these tested successfully), stored in php variables. I tried to run a series of if statements to change the WHERE and GROUP BY clauses based on the values of the ajax data variables and then concat then into my SELECT statement. I try the same method for building the column headers and the table itself. When I test the current code, the table headers display (the first column is empty because of the variable) but the columns aren't built. I don't receive any errors when I inspect the page and my ajax variables display the appropriate values.
The problem is definately with the IF statements but I'm not sure how to fix that.
Note: the SQL statements works perfectly when I manually enter a WHERE or GROUP BY clause using the same values I'm trying to store in variables.
MY CODE:
AJAX Response:
//Get Table Type.
if (isset($_POST['revenueTblType'])) {
$revenueTblType = $_POST['revenueTblType'];
print_r($revenueTblType);
};
//Get Report Type
if (isset($_POST['revenueWO'])) {
$revenueWO = $_POST['revenueWO'];
print_r($revenueWO);
};
//Get date include value.
if (isset($_POST['revenueWODate'])) {
$revenueWODate = $_POST['revenueWODate'];
print_r($revenueWODate);
};
//Get date range.
$revenuefromajax=$_POST['revenuefrom'];
$revenuetoajax=$_POST['revenueto'];
$revenuefromstring = strtotime($revenuefromajax);
$revenuetostring = strtotime($revenuetoajax);
$revenuefrom=date("Y-m-d", $revenuefromstring);
$revenueto=date("Y-m-d", $revenuetostring);
//Get selected Status Values.
if (isset($_POST['revenue_checkboxes'])) {
$revenue_check = $_POST['revenue_checkboxes'];
};
IF STATEMENTS and TABLE BUILD:
///////////// Select Data and Display it in a table. //////////////
//$groupbyclause = "";
if ($revenueTblType=='Customer') {
$groupbyclause="x.company ASC";
$columnheader='Customer';
$columnname='company';
}
else if ($revenueTblType=='Revenue Category') {
$groupbyclause="x.revenue ASC";
$columnheader='Revenue Category';
$columnname='revenue';
}
//$whereclause = "";
if (($revenueWO=='Completed Workorders') and ($revenueWODate=='All Workorders')) {
$whereclause="x.stagestatus = 'Complete'";
}
else if (($revenueWO=='Completed Workorders') and ($revenueWODate=='Workorder Date Range')) {
$whereclause ="x.stagestatus = 'Complete' AND x.shippeddate BETWEEN '".$revenuefrom."' AND '".$revenueto."'";
}
else if ($revenueWO=='Workorder Status') {
$whereclause ="x.stagestatus IN (". implode(',', array_map(function($item) {return '"' . $item . '"'; }, $revenue_check)) .")";
}
echo "<BR>";
echo "<BR>";
//SELECT statement pulls ALL COMPLETED history info by CUSTOMER.
$sql="SELECT x.company, x.revenue, x.stagestatus, x.shippeddate, FORMAT(SUM(x.totprice), 2) as totalprice, FORMAT(SUM(x.sgtotquantity), 2) as totqty, FORMAT(SUM(x.sgtotalsqft), 2) as sgtotsqft, FORMAT(SUM(x.totprice)/SUM(x.sgtotalsqft), 2) as avgsqftrevenue, FORMAT(SUM(x.totprice)/SUM(x.sgtotquantity), 2) as avgunitrevenue FROM (SELECT t1.company, t1.revenue, t1.stagestatus, t1.shippeddate, t1.id, TRIM(LEADING '$' FROM t1.totalprice) AS totprice, t2.invoiceid, SUM(t2.quantity) AS sgtotquantity, SUM(t2.width * t2.height * t2.quantity ) /144 AS sgtotalsqft, (t1.totalprice/(SUM(t2.width * t2.height * t2.quantity ) /144)) as avgsqftrev, (t1.totalprice) / SUM(t2.quantity)) AS avgunitrev
FROM invoices AS t1 INNER JOIN lineitems AS t2 ON t1.id = t2.invoiceid
WHERE (t2.invoiceid = t1.id)
GROUP BY t1.id) x
WHERE '".$whereclause."'
GROUP BY ".$groupbyclause.""; //this line edited per comment suggestions.//
$result = $conn->query($sql);
echo "<table id='revenueReportA' align='center' class='report_DT'>
<thead>
<tr>
<th>".$columnheader."</th>
<th>Total Revenue</th>
<th>Total SQ FT</th>
<th>AVG Revenue Per SQ FT</th>
<th>Total Number of Units</th>
<th>AVG Revenue Per Unit</th>
</tr>
</head>";
if ($result = $conn->query($sql)) {
// fetch associative array
while ($row = $result->fetch_assoc()) {
echo "<tbody>";
echo "<tr>";
echo "<td>" . $row[$columnname] . "</td>";
echo "<td>" ."$". $row['totalprice'] . "</td>";
echo "<td>" . $row['sgtotsqft'] ." ". "ft<sup>2</sup>". "</td>";
echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>";
echo "<td>" . $row['totqty'] . "</td>";
echo "<td>" ."$". $row['avgunitrevenue'] . "</td>";
echo "</tr>";
echo "</tbody>";
}//End table while.
echo "</table>";
echo "<BR>";
}//End table if.
///////////////////////////////////////////////////////////////////////////////
//Free the result variable.
$result->free();
//Close the Database connection.
$conn->close();
All suggestions are welcome. Thank you!
You have too many ' characters in query. Currently all of your WHERE statement is quoted as well as GROUP BY statement.
Change this:
WHERE '".$whereclause."'
GROUP BY '".$groupbyclause."'"
To this:
WHERE ".$whereclause."
GROUP BY ".$groupbyclause
Be caution with last line:
//SELECT statement pulls ALL COMPLETED history info by CUSTOMER.
$sql="SELECT x.company, x.revenue, x.stagestatus, x.shippeddate, FORMAT(SUM(x.totprice), 2) as totalprice, FORMAT(SUM(x.sgtotquantity), 2) as totqty, FORMAT(SUM(x.sgtotalsqft), 2) as sgtotsqft, FORMAT(SUM(x.totprice)/SUM(x.sgtotalsqft), 2) as avgsqftrevenue, FORMAT(SUM(x.totprice)/SUM(x.sgtotquantity), 2) as avgunitrevenue FROM (SELECT t1.company, t1.revenue, t1.stagestatus, t1.shippeddate, t1.id, TRIM(LEADING '$' FROM t1.totalprice) AS totprice, t2.invoiceid, SUM(t2.quantity) AS sgtotquantity, SUM(t2.width * t2.height * t2.quantity ) /144 AS sgtotalsqft, (t1.totalprice/(SUM(t2.width * t2.height * t2.quantity ) /144)) as avgsqftrev, (t1.totalprice) / SUM(t2.quantity)) AS avgunitrev
FROM invoices AS t1 INNER JOIN lineitems AS t2 ON t1.id = t2.invoiceid
WHERE (t2.invoiceid = t1.id)
GROUP BY t1.id) x
WHERE ".$whereclause."
GROUP BY ".$groupbyclause."";

sum mysql table column data where id is the same in php SELECT statement

I need to display an html table with data from two different tables, invoices and lineitems where invoices.id=lineitems.invoiceid. However, each row in invoices can have several lineitem rows that connect to it as invoices is the customers' order and lineitems is the table containing all the products for each order. I need to sum up the values from lineitems.quantity for every row where the invoiceid is the same so my html table can display the total quantity for the order. Is there a way to do that within my select statement for my html table?
Right now, when I display my table, I get the same invoice order listed repeatedly for each lineitem row associated with it (where the only html table column data that's different per row is the quantity).
MySQL SELECT statement:
$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.orderdate BETWEEN '".$revenuefrom."' AND '".$revenueto."' AND invoices.stagestatus IN (". implode(',', array_map(function($item) {return '"' . $item . '"'; }, $revenue_check)) .")
ORDER BY invoices.id DESC";
//Display daterange and table.
echo 'Displaying results for: '.$revenuefrom.' to '.$revenueto.'. '.'<BR><BR><BR>';
$result = $conn->query($sql);
echo "<table id='revenueReportA' align='center' class='report_DT'>
<tr>
<th>Customer</th>
<th>Stage Status</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['stagestatus'] . "</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>";
NOTE: Due to the pre-existing code design (I inherited...), setting up a trigger is not an option and trying to run the calculation and insert that value into another column in invoices is seeming impossible from the application side (again due to the way the previous programmer designed the update/insert for invoices and lineitems). If anyone is curious about that code, please refer to the following link where I asked how complete this same task via the application side:
get sum() value from user input going into one table and store in another table using php
Any suggestions are greatly appreciated as I have tried several different methods for achieving the desired outcome.
Thank you!

looping on mysql query

im busy with a script to load mysql data in php variablen.
My database is an gps tracking database with different users and gps coordinates in a table.
The problem is. each gps update has its own ID... for an example if userA posting his gps location that will be id 1, but when user B also post their location 5 minutes later this is id 2, when userA post their location again 10 minutes later, that will be id 3.
Now is the question. How can i sort the newest gps locations for each user.
This is my table structure and my code:
//Tabel selecteren en wat opties defineren
$posities = mysqli_query($raw,"SELECT * FROM positions INNER JOIN devices ON positions.device_id = devices.id ORDER BY positions.id DESC");
//Aantal gebruikers tellen in de devices tabel aanroepen via $aantalgb
$query = mysqli_query($raw,"SELECT COUNT(id) FROM devices");
$row = mysqli_fetch_row($query);
$aantalgb = $row[0];
mysqli_free_result($query);
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Naam</th>
<th>Tijd</th>
<th>Lat</th>
<th>Lon</th>
<th>Snelheid</th>
</tr>";
while($pos = mysqli_fetch_array($posities)) {
echo "<tr>";
echo "<td>" . $pos['device_id'] . "</td>";
echo "<td>" . $pos['name'] . "</td>";
echo "<td>" . $pos['time'] . "</td>";
echo "<td>" . $pos['latitude'] . "</td>";
echo "<td>" . $pos['longitude'] . "</td>";
echo "<td>" . $pos['speed'] . "</td>";
echo "</tr>";
}
echo "</table>";
Thank you!

PHP MySQL Queries - Addition

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;

Categories