taking two array and looping it with mysql query to fetch result - php

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

Related

php mysql using nested query

I am trying to find if two runners have ever ran in the same race. The two runners are Peter Smith and Diane Peters.
$resultRaceType = mysqli_query($db,"SELECT DISTINCT date,time FROM results where runner = 'Peter, Smith' ");
while($row = mysqli_fetch_array( $resultRaceType ))
{
$resultRaceType1 = mysqli_query($db,"SELECT * FROM results where date = ' " . $row['date'] . " ' and time = ' " . $row['time'] . " ' and runner = 'Diane, Peters'");
while($row1 = mysqli_fetch_array( $resultRaceType1 ))
{
echo "<tr >";
echo "<td>";
echo $row1['date'];
echo " - " . $row1['time'];
echo "</td>";
echo "<tr>";
}
}
The above code works, but only if I limit the first select to LIMIT 50. So I can see that it is timing out. My table has over 100K rows. I know I am doing something wrong but cant see what it is.
Thanks for any help you guy's can give me.
Try:
SELECT a.date, a.time FROM results a
JOIN results b ON (a.date = b.date AND a.time = b.time)
WHERE a.runner='Peter, Smith' AND b.runner='Diane, Peters';

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

Run 2 queries together but execute separately

I currently have 2 separate queries which i need to run together, but execute separately, and i was wondering what would be the best practice to do this.
I have a query that dynamically prints out restaurants each and every time one is added in the admin page, and i have a query that works out if the restaurant is open or closed. I thought this would be simple by executing the 2 separate queries then saving the opening times echo into a variable and putting this variable inside the loop, however, that does not seem to be working. By not working I mean the wrong id is being called as the opening hrs query is before the dynamic print out query, and when it is after the query works the plan, but then my echo/print out variable does not work. I am struck and have no idea how to move forward.
Opening hr query
$query = mysqli_query($dbc, "SELECT * FROM Opening_hrs
WHERE Restaurant_ID='$rest_id' AND Day_of_week = DATE_FORMAT(NOW(), '%w')
AND CURTIME() BETWEEN Open_time AND Closing_time");
$run_qu = $dbc->query($query);
if($run_qu->num_rows>0){
while($row_qu=$run_qu->fetch_assoc()){
$message= "open" .$row_qu["Open_time"]."</br>";
}
} else {
$message=$message. "close".$row_qu["Closing_time"]."</br>";
}
Dynamic query
$sql = mysqli_query($dbc, "SELECT Rest_Details.Resturant_ID, Rest_Details.Resturant_name,,Delivery_Pcode.Pcode
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE '%" . $pcode . "%'") or die("could not search!");
echo var_dump($sql);
$count = mysqli_num_rows($sql);
if ($count === 0) {
$output = '<b>we dont deliver to ' . $pcode . '</b></br>';
} else {
$i = 1;
}
while ($row_prods = mysqli_fetch_array($sql)) {
$rest_id = $row_prods['Resturant_ID'];
$rest_name = $row_prods['Resturant_name'];
$output = $output . '<div id="products">' .
' <p id="rest_name">' . $rest_name . '</p>' .
'<p> '.$message.' </p>' .;
$i++;
}
}
You should join the two queries:
SELECT
Rest_Details.Resturant_ID,
Rest_Details.Resturant_name,
Delivery_Pcode.Pcode,
Opening_hrs.Open_time,
Opening_hrs.Closing_time
FROM Rest_Details
JOIN Deliver_Pcode ON Delivery_Pcode.Restaurant_ID=Rest_Details.Restaurant_ID
LEFT JOIN Opening_hrs ON Opening_Hrs.Restaurant_ID=Rest_Details.Restaurang_ID
AND Day_of_week = WEEKDAY(NOW()) AND CURTIME() BETWEEN Open_time AND Closing_time
WHERE Delivery_Pcode.Pcode LIKE '%$pcode%'
Because it's a LEFT JOIN, Open_time and Closing_time will be filled in if the restaurant is open, otherwise they will be NULL. So the PHP that displays the results can check this:
while ($row_prods = mysqli_fetch_array($sql)) {
$rest_id = $row_prods['Resturant_ID'];
$rest_name = $row_prods['Resturant_name'];
$output .= '<div id="products">' .
' <p id="rest_name">' . $rest_name . '</p>';
if ($row_prods['Open_time']) {
$output .= '<p> open ' . $row_prods['Open_time'] . ' close ' . $row_prods['Close_time'];
}
$output .= "</div>";
$i++;
}
If you want to have a list of all restaurants which will deliver within a certain range of plzs and their opening hours then you could use this query:
$sql = '
SELECT
Rest_Details.Resturant_ID,
Rest_Details.Resturant_name,
Delivery_Pcode.Pcode,
EXISTS(
SELECT *
FROM Opening_hrs
WHERE
Restaurant_ID=' . $rest_id . ' AND
Day_of_week = DATE_FORMAT(NOW(), "%w") AND
CURTIME() BETWEEN Open_time AND Closing_time
) as isOpen
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE "%' . $pcode . '%"
';
Mysql exist() will return 1 if one or more rows match the the specified query and 0 otherwise. as isOpen will make this value accesibble in column with name isOpen.

PHP, MySQL - JOINs

I am new to PHP and I just cannot figure out my code. I am using MySQL and PHP.
table: person
PK: personID
Other fields: lastName, firstName, hireDate, imgName
table: validMajors
PK: majorAbbrev
Other Fields: majorDesc
(Junction) table: personMajors
personID, majorAbbrev
When I run my code (using NATURAL JOIN) it will display the image, last&first name, and hire date. Which is great! But I need it to display their majors as well (I would like the majorAbbrev to be displayed). It also does not display people who are in the person table but are not in the personMajors table, which is an issue because we have staff members in the person table (who do not have a major since they are not a student)
Here is my code:
<table align="center">
<?php
$connection = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);
if ( mysqli_connect_errno() ) {
die( mysqli_connect_error() );
}
$sql = "SELECT * FROM person NATURAL JOIN personMajors ORDER BY lastName";
if ($result = mysqli_query($connection, $sql)) {
// loop through the data
$columns=4;
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
if($i % $columns ==0){
echo "<tr>";
}
echo "<td class='staffImage badgeText frameImage displayInLine'>" . "<img src='images/staff/".$row['imgName'].".jpg'>". "<br>".
"<strong>" . $row['firstName'] . "</strong>" ." ".
"<strong>" . $row['lastName'] . "</strong>" . "<br>" .
"Hire Date: ".$row['hireDate'] ."</td>";
"Major: " .$row['majorAbbrev'] ."</td>"; //Does not display
if($i % $columns == ($columns - 1)){
echo "</tr>";
}
$i++;
}
// release the memory used by the result set
mysqli_free_result($result);
}
// close the database connection
mysqli_close($connection);
?>
</table>
Any ideas/solution will be greatly appreciated!
Because you are not concatenating your php properly. You ended (;) your echo after displaying the $row["lastName"].
You can try these to join the three tables:
SELECT * FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Or you can define what columns to call in your query:
SELECT person.personID,
person.lastName,
person.firstName,
person.hireDate,
person.imgName,
validMajors.majorAbbrev,
validMajors.majorDesc
FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Then you can call the results with the way you are calling it right now (cleaner version):
echo '<td class="staffImage badgeText frameImage displayInLine">
<img src="images/staff/'.$row["imgName"].'.jpg"><br>
<strong>'.$row["firstName"].'</strong>
<strong>'.$row["lastName"].'</strong><br>
Hire Date: '.$row["hireDate"].'
Major: '.$row["majorAbbrev"].'
</td>';
(Second try): Is the person to major relationship one to one or one to many?
OK, this SELECT Statement should work:
SELECT person.*, validMajors.* FROM person AS p, validMajors AS vm, personMajors AS pm WHERE p.personID = pm.personID AND pm.majorAbbrev = vm.majorAbbrev

How to add up votes in a table and display it on screen

i have a php code which selects and shows data from my 'elections' table. i have another table called 'votes' which contains all the votes by users. how do i select the two tables and show the party that has had the most votes? so if labour had 5 votes for example and lib dems had 3 votes, how would i show on screen that 'labour has won this election with __ votes? my php is as follows:
<?php
$id = $_GET['election'];
$result = mysql_query("SELECT election_id, name_of_election, date, month, year FROM elections WHERE election_id = '$id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo '<hr><h3>There Aren\'t Any Elections Setup Yet</h3><hr> ';
} else {
echo '<hr><h3>Vote Count</h3><hr>';
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name_of_election']. "</td>";
echo "<br/><br/><td>" . $info['date']. ' '. $info['month']. ' ' . $info['year']. "</td>";
echo "<br/><br/><td>" . '<hr>' . "</td>";
}
}
echo "</tr>";
echo "</table>";
?>
my database table consists of the following fields:
(dont ask about the date fields)
elections: election_id, name_of_election, date, month, year, party1, party2, party3, status
votes: vote_id, election_id, ni, party
any ideas?
This will give you the party and count for selected election in descending order of count:
$result = mysql_query(
sprintf("
SELECT votes.party, COUNT(votes.vote_id)
FROM votes
WHERE election_id = %d
GROUP BY election_id, votes.party
ORDER BY COUNT(votes.vote_id) DESC",
mysql_real_escape_string($id)
)
);
Edit: To display the first row (which will be the party with the most votes):
list($party, $votes) = mysql_fetch_row($result);
echo '<p>'.$party.' won with '.$votes.'</p>';

Categories