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."";
Related
I need to pull column data from two tables, run calculations on the data with the result saved as an alias, and then sum those results into other alias' to display in a php table. I am trying to achieve this by creating a derived table within my SELECT statement but it doesn't work. I don't receive any errors but my table only displays the column headers.
CODE:
$sql = "SELECT x.company, x.stagestatus, x.shippeddate, SUM(x.totprice) as totalprice, SUM(x.sgtotquantity) as sgtotqty, SUM(x.sgtotalsqft) as sgtotsqft, SUM(x.avgsqftrev) as avgsqftrevenue, SUM(x.avgunitrev) as avgunitrevenue FROM (SELECT t1.company, t1.stagestatus, t1.shippeddate, t1.id, FORMAT(TRIM(LEADING '$' FROM t1.totalprice), 2) AS totprice, t2.invoiceid, SUM(t2.quantity) AS sgtotqauntity, FORMAT(SUM(t2.width * t2.height * t2.quantity ) /144, 2) AS sgtotalsqft, FORMAT((TRIM(LEADING '$' FROM t1.totalprice)/(SUM(t2.width * t2.height * t2.quantity ) /144)), 2) as avgsqftrev, FORMAT((TRIM(LEADING '$' FROM t1.totalprice) / SUM(t2.quantity)), 2) 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 x.stagestatus='Complete'
GROUP BY x.company ASC";
This code breaks but when I use the smaller pieces individually, it works ok.
EX:
$sql="SELECT invoices.id, invoices.orderdate, invoices.stagestatus, FORMAT(TRIM(LEADING '$' FROM invoices.totalprice), 2) AS totalprice, clients.company, lineitems.invoiceid, SUM(lineitems.quantity) AS sgtotqty, FORMAT(SUM(lineitems.width * lineitems.height * lineitems.quantity ) /144, 2) AS sgtotsqft, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice)/(SUM(lineitems.width * lineitems.height * lineitems.quantity ) /144)), 2) as avgsqftrevenue, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice) / SUM(lineitems.quantity)), 2) AS avgunitrevenue
FROM clients
INNER JOIN invoices ON clients.id = invoices.clientid
INNER JOIN lineitems ON invoices.id = lineitems.invoiceid
WHERE (lineitems.invoiceid = invoices.id) AND invoices.orderdate BETWEEN '".$revenuefrom."' AND '".$revenueto."' AND invoices.stagestatus IN (". implode(',', array_map(function($item) {return '"' . $item . '"'; }, $revenue_check)) .")
GROUP BY invoices.id DESC";
This code works just fine and groups all data by invoices.id. However, the project needs were adjusted and now everything must group by invoices.company. When I simply try to group by invoices.company instead of invoices.id, my table completes but the values for each company row are very inaccurate, (aren't sum()ing right).
PHP CODE where table is built:
$result = $conn->query($sql);
echo "<table id='revenueReportA' align='center' class='report_DT'>
<thead>
<tr>
<th>Customer</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['company'] . "</td>";
echo "<td>" ."$". $row['totalprice'] . "</td>";
echo "<td>" . $row['sgtotsqft'] ." ". "ft<sup>2</sup>". "</td>";
echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>";
echo "<td>" . $row['sgtotqty'] . "</td>";
echo "<td>" ."$". $row['avgunitrevenue'] . "</td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
echo "<BR>";
All help is appreciated.
Thank you,
I had a spelling mistake and a formatting issue. By formatting the final data instead of formatting within the embedded SELECT statement, my table data was accurate.
Successful CODE:
$sql = "SELECT x.company, x.stagestatus, x.shippeddate, FORMAT(SUM(x.totprice), 2) as totalprice, FORMAT(SUM(x.sgtotquantity), 2) as sgtotqty, FORMAT(SUM(x.sgtotalsqft), 2) as sgtotsqft, FORMAT(SUM(x.avgsqftrev), 2) as avgsqftrevenue, FORMAT(SUM(x.avgunitrev), 2) as avgunitrevenue FROM (SELECT t1.company, 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, (TRIM(LEADING '$' FROM t1.totalprice)/(SUM(t2.width * t2.height * t2.quantity ) /144)) as avgsqftrev, (TRIM(LEADING '$' FROM 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 x.stagestatus='Complete'
GROUP BY x.company ASC";
Thank you!!!
I need to pull column data from two tables, run calculations on the data with the result saved as an alias, and then sum those results into other alias' to display in a php table. I am trying to achieve this by creating a derived table within my SELECT statement but it doesn't work. I don't receive any errors but my table only displays the column headers.
CODE:
$sql = "SELECT x.company, x.stagestatus, x.shippeddate, SUM(x.totprice) as totalprice, SUM(x.sgtotquantity) as sgtotqty, SUM(x.sgtotalsqft) as sgtotsqft, SUM(x.avgsqftrev) as avgsqftrevenue, SUM(x.avgunitrev) as avgunitrevenue FROM (SELECT t1.company, t1.stagestatus, t1.shippeddate, t1.id, FORMAT(TRIM(LEADING '$' FROM t1.totalprice), 2) AS totprice, t2.invoiceid, SUM(t2.quantity) AS sgtotqauntity, FORMAT(SUM(t2.width * t2.height * t2.quantity ) /144, 2) AS sgtotalsqft, FORMAT((TRIM(LEADING '$' FROM t1.totalprice)/(SUM(t2.width * t2.height * t2.quantity ) /144)), 2) as avgsqftrev, FORMAT((TRIM(LEADING '$' FROM t1.totalprice) / SUM(t2.quantity)), 2) 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 x.stagestatus='Complete'
GROUP BY x.company ASC";
This code breaks but when I use the smaller pieces individually, it works ok.
EX:
$sql="SELECT invoices.id, invoices.orderdate, invoices.stagestatus, FORMAT(TRIM(LEADING '$' FROM invoices.totalprice), 2) AS totalprice, clients.company, lineitems.invoiceid, SUM(lineitems.quantity) AS sgtotqty, FORMAT(SUM(lineitems.width * lineitems.height * lineitems.quantity ) /144, 2) AS sgtotsqft, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice)/(SUM(lineitems.width * lineitems.height * lineitems.quantity ) /144)), 2) as avgsqftrevenue, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice) / SUM(lineitems.quantity)), 2) AS avgunitrevenue
FROM clients
INNER JOIN invoices ON clients.id = invoices.clientid
INNER JOIN lineitems ON invoices.id = lineitems.invoiceid
WHERE (lineitems.invoiceid = invoices.id) AND invoices.orderdate BETWEEN '".$revenuefrom."' AND '".$revenueto."' AND invoices.stagestatus IN (". implode(',', array_map(function($item) {return '"' . $item . '"'; }, $revenue_check)) .")
GROUP BY invoices.id DESC";
This code works just fine and groups all data by invoices.id. However, the project needs were adjusted and now everything must group by invoices.company. When I simply try to group by invoices.company instead of invoices.id, my table completes but the values for each company row are very inaccurate, (aren't sum()ing right).
PHP CODE where table is built:
$result = $conn->query($sql);
echo "<table id='revenueReportA' align='center' class='report_DT'>
<thead>
<tr>
<th>Customer</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['company'] . "</td>";
echo "<td>" ."$". $row['totalprice'] . "</td>";
echo "<td>" . $row['sgtotsqft'] ." ". "ft<sup>2</sup>". "</td>";
echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>";
echo "<td>" . $row['sgtotqty'] . "</td>";
echo "<td>" ."$". $row['avgunitrevenue'] . "</td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
echo "<BR>";
All help is appreciated.
Thank you,
I had a spelling mistake and a formatting issue. By formatting the final data instead of formatting within the embedded SELECT statement, my table data was accurate.
Successful CODE:
$sql = "SELECT x.company, x.stagestatus, x.shippeddate, FORMAT(SUM(x.totprice), 2) as totalprice, FORMAT(SUM(x.sgtotquantity), 2) as sgtotqty, FORMAT(SUM(x.sgtotalsqft), 2) as sgtotsqft, FORMAT(SUM(x.avgsqftrev), 2) as avgsqftrevenue, FORMAT(SUM(x.avgunitrev), 2) as avgunitrevenue FROM (SELECT t1.company, 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, (TRIM(LEADING '$' FROM t1.totalprice)/(SUM(t2.width * t2.height * t2.quantity ) /144)) as avgsqftrev, (TRIM(LEADING '$' FROM 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 x.stagestatus='Complete'
GROUP BY x.company ASC";
Thank you!!!
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!
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>";
<?php
//db connection goes here
$arr=array('12:30:00','01:30:01','02:30:01','03:30:01','04:30:01','05:30:01','06:30:01','07:30:01');
$arr1=array('01:30:00','02:30:00','03:30:00','04:30:00','05:30:00','06:30:00','07:30:00','08:30:00');
$cnt=count($arr);
for($i=0;$i<$cnt;$i++){
$sql="SELECT count(*) FROM report WHERE DATE_FORMAT(dt,'%H:%m:%i') BETWEEN $arr[$i] AND $arr1[$i]";
}
//fetching in while and echo
this is my script that i am trying which will generate report counting number of user and number of application from two different table report and report1.
the report will be like
Time count Logged In user Count-Apps
12:30:00-01:30:00
01:30:01-02:30:00
02:30:01 -03:30:00
03:30:01-04:30:00
04:30:01-05:30:00
05:30:01-06:30:00
06:30:01-07:30:00
07:30:01-08:30:00
08:30:01-09:30:00
report table for counting number of user
user datetimeuser(datetime)
a 12:30:00
b 01:30:00
c 01:30:01
d 02:30:00
report1 table for counting number of apps
user datetimeuser(datetime)
a 12:30:00
b 01:30:00
c 01:30:01
d 02:30:00
previously i have done a script which does the work but its slowing the server as my script will be placed in cron job firing in 1 hour interval and fetching the result
previous.php
$time_ranges = array(
array('12:30:00','01:30:00'),
array('01:30:01', '02:30:00'),
array('02:30:01', '03:30:00'),
array('03:30:01', '04:30:00'),
array('04:30:01', '05:30:00'),
array('05:30:01', '06:30:00'),
array('06:30:01', '07:30:00'),
array('07:30:01', '08:30:00'),
array('08:30:01', '09:30:00'),
);
$sql="SELECT sub0.TimeRange, sub0.number, COUNT(*) AS countapps
FROM
(
SELECT
CASE
";
foreach ($time_ranges as $r) {
$sql .= "
WHEN DATE_FORMAT(dt,'%H:%i:%s') BETWEEN '$r[0]' and '$r[1]'
THEN STR_TO_DATE(CONCAT(CURDATE(), ' ', '$r[0]'), '%Y-%m-%d %H:%i:%s') ";
}
$sql .= "
ELSE NULL
END AS StartRange,
CASE ";
foreach ($time_ranges as $r) {
$sql .= "
WHEN DATE_FORMAT(dt,'%H:%i:%s') BETWEEN '$r[0]' and '$r[1]'
THEN STR_TO_DATE(CONCAT(CURDATE(), ' ', '$r[1]'), '%Y-%m-%d %H:%i:%s') ";
}
$sql .= "
ELSE NULL
END AS EndRange,
CASE ";
foreach ($time_ranges as $r) {
$sql .= "
WHEN DATE_FORMAT(dt,'%H:%i:%s') BETWEEN '$r[0]' and '$r[1]'
THEN '$r[0]-$r[1]' ";
}
$sql .= "
ELSE NULL
END AS TimeRange,
COUNT(*) as number
FROM report
WHERE DATE_FORMAT(dt,'%Y:%m:%d')=DATE(CURDATE())
GROUP BY StartRange, EndRange, TimeRange
HAVING TimeRange IS NOT NULL
) sub0
LEFT OUTER JOIN report1
ON report1.dt BETWEEN sub0.StartRange AND sub0.EndRange
GROUP BY sub0.TimeRange, sub0.number";
$query=mysql_query($sql);
echo'<html>
<head>
<title>Count User Info TimeWise</title>
</head>
<h1>Count User</h1>
<table border="3" cellspacing="2">
<tr>
<th>range</th>
<th>count</th>
<th>Apps Count</th>';
while($row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>" . $row['TimeRange'] . "</td>";
echo "<td>" . $row['number'] . "</td>";
echo "<td>" . $row['countapps'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</html>";
?>
i want to make the mysql query shorter and more precise by taking only two array and looping it.but could not really make it.please help.how can i do this taking two array and then counting(array) and for loop it and count statement in mysql
$arr=array('12:30:00','01:30:01','02:30:01','03:30:01','04:30:01','05:30:01','06:30:01','07:30:01');
$arr1=array('01:30:00','02:30:00','03:30:00','04:30:00','05:30:00','06:30:00','07:30:00','08:30:00');
$cnt=count($arr);
for($i=0;$i<$cnt;$i++){
$sql="SELECT count(*) AS test FROM report WHERE DATE_FORMAT(dt,'%H:%m:%i') BETWEEN $arr[$i] AND $arr1[$i]";
Possibly dynamically build up a select to return the times and then join that against you report table:-
$numbers = array();
foreach($arr AS $key=>$value)
{
$numbers[] = "SELECT '".$arr[$key]."' AS StartRange, '".$arr1[$key]."' AS EndRange ";
}
$dates_select = "(".implode(" UNION ",$numbers).") sub0";
$sql="SELECT sub0.StartRange, sub0.EndRange, count(report.dt)
FROM $dates_select
LEFT OUTER JOIN report
ON DATE_FORMAT(report.dt,'%H:%m:%i') BETWEEN sub0.StartRange AND sub0.EndRange
GROUP BY sub0.StartRange, sub0.EndRange";