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.
Related
Im sorry for my bad english but this is the best i can.
I am trying to make a script that get's the item values of one line in my
for this example i'll be using the row with ID 2.
The first query is working correctly and getting the 2 values of 1items and 2items and deletes the ; that comes with it.
But the second part seems a little bit harder and i can't solve it.
The query is getting id, base_item from the table
The last 2 Outputs marked red are the one's that are matching 1items & 2items
I'm trying to let the if statement filter the $item1 as id in the item table and output the baseitem of the found row
same goes for item2
I'm using MySQL & MySQLi because this cms doesnt support newer versions of PHP yet.
<?php
$query = "SELECT * FROM logs_client_trade ORDER by id DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$item1 = rtrim($row['1items'],"; ");
$item2 = rtrim($row['2items'],"; ");
echo("<tr>");
echo("<td>" . $row['id'] . "</td>");
echo("<td>" . $row['1id'] . "</td>");
echo("<td>" . $row['2id'] . "</td>");
$userinfo = "SELECT id, base_item FROM items LIMIT 1";
$result2 = mysql_query($userinfo) or die(mysql_error());
while($row2 = mysql_fetch_assoc($result2)){
echo("<td>");
if($row2['id'] == $item1){ echo $row2['baseitem']; } else echo "Not available";
echo ("</td>");
echo("<td>");
if($row2['id'] == $item1){ echo $row2['baseitem']; } else echo "Not available";
echo ("</td>");
}
$tradetime = $row['timestamp'];
$date = date("d M Y - H:i:s", $tradetime);
echo("<td>$date</td></tr>");
}
?>
You forgot the while loop for the second query:
$userinfo = mysql_query("SELECT id, base_item FROM items");
while($get2 = $userinfo->fetch_assoc()) {
$baseid = $get2['id'];
$baseitem = $get2['baseitem'];
echo("<tr>");
[...]
}
In addition to that, your code is a mess. In the second loop you are still listing the rows from the logs table... I suggest you to review carefully your code, being careful on how you are using the different $row and $get2 arrays.
You can use a JOIN to get all of the info with one SQL statement:
SELECT *
FROM `logs_client_trade` a
LEFT JOIN `items` b
ON REPLACE(a.`1items`,';','') = b.`id`
LEFT JOIN `items` c
ON REPLACE(a.`2items`,';','') = c.`id`
ORDER by a.`id` DESC
UPDATE:
Here's the PHP code that will run the query and output the table rows. I've specified the column names based on the code in the original question.
<?php
$query = "SELECT
a.`id`,
a.`1id`,
a.`2id`,
a.`1items`,
a.`1items`,
IFNULL(b.`baseitem`,'Not Available') as `baseitem1`,
IFNULL(c.`baseitem`,'Not Available') as `baseitem2`,
DATE_FORMAT(a.`timestamp`,'%d %m %Y - %H:%i:%s') as `tradetime`
FROM `logs_client_trade` a
LEFT JOIN `items` b
ON REPLACE(a.`1items`,';','') = b.`id`
LEFT JOIN `items` c
ON REPLACE(a.`2items`,';','') = c.`id`
ORDER by a.`id` DESC
";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$item1 = rtrim($row['1items'],"; ");
$item2 = rtrim($row['2items'],"; ");
echo "<tr>\r\n";
echo " <td>" . $row['id'] . "</td>\r\n";
echo " <td>" . $row['1id'] . "</td>\r\n";
echo " <td>" . $row['2id'] . "</td>\r\n";
echo " <td>" . $row['baseitem1'] . "</td>\r\n";
echo " <td>" . $row['baseitem2'] . "</td>\r\n";
echo " <td>" . $row['tradetime'] . "</td>\r\n";
echo("</tr>\r\n");
}
?>
I am working on a php script that will get the required information and display it in an xml. For some reason my brin isn't work and I don't know how to do the query. The database has two tables that I want to pull information from. Both tables have one thing in common which is 'id_member'. Themes table has a bunch of junk in it - so it has 4 coulms - 'id_member', 'id_theme', 'varible', and 'value'. There are two items in 'varible' that I want to filter (show them and not the rest) "cust_armaus" and "cust_armamo" then value will show the value of course. So in the table Themes it will have id_member listed more than once to show the different varibles. This is what I got that isn't working for me:
<?php
header('Content-Type: text/xml');
$username="database_username";
$password="database_password";
$database="database_name";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
echo "<?xml version=\"1.0\"?>\n".
"<!DOCTYPE squad SYSTEM \"squad.dtd\">\n".
"<?xml-stylesheet href=\"squad.xsl?\" type=\"text/xsl\"?>\n";
?>
<squad nick="Team Tag">
<name>Team Name</name>
<email>contact#team.com</email>
<web>http://www.team.com</web>
<picture>teamlogo.paa</picture>
<title>This is the Team motto</title>
<?php
// smf_themes -> id_member =
// smf_themes -> variable for cust_armaus & cust_usermo
// smf_themes -> value <- get for cust_armaus & cust_usermo
// smf_members -> real_name = profile_name & name
// smf_members -> email_address = email - NO
$memberSQL = mysql_query("SELECT id_member AS id, real_name FROM smf_members");
$member = mysql_fetch_array($memberSQL);
$armausSQL = mysql_query("SELECT id_member, variable, value AS arma_id FROM smf_themes WHERE id_member='$member[id]' AND variable='cust_armaus'");
$armaid = mysql_fetch_array($armausSQL);
$armamoSQL = mysql_query("SELECT id_member, variable, value AS motto FROM smf_themes WHERE id_member='$member[id]' AND variable='cust_usermo'");
$armamo = mysql_fetch_array($armamoSQL);
$num=mysql_numrows($member, $armaid, $armamo);
mysql_close();
$i=0;
while ($i < $num) {
$profile_id = mysql_result($armaid,$i,"value");
$profile_name = mysql_result($member,$i,"real_name");
$profile_remark = mysql_result($armamo,$i,"value");
$profile_username = mysql_result($member,$i,"real_name");
//$profile_email = mysql_result($result,$i,"email");
//$profile_icq = mysql_result($result,$i,"icq");
echo "<member id=\"$profile_id\" nick=\"$profile_name\">" .
"<name>$profile_name</name>".
"<email>$profile_email</email>".
"<icq>$profile_icq</icq>".
"<remark>$profile_remark</remark>".
"</member>\n";
$i++;
}
?>
</squad>
The mysql interface is deprecated. New development should use either mysqli or PDO.
Assuming you only one one value of the cust_armaus and cust_usermo rows for each smf_members, you could use correlated subqueries in the SELECT list, and return just a single query that returns a single row for each row in smf_members. Something like this:
SELECT m.id_member AS id
, m.real_name
, (SELECT a.value
FROM smf_themes a
WHERE a.id_member = m.id_member
AND a.variable = 'cust_armaus'
ORDER BY a.value LIMIT 1
) AS cust_armaus
, (SELECT u.value
FROM smf_themes u
WHERE u.id_member = m.id_member
AND u.variable = 'cust_usermo'
ORDER BY u.value LIMIT 1
) AS cust_usermo
FROM smf_members m
ORDER BY m.id_member
If the (id_member,variable) tuple is guaranteed to be unique in smf_themes, you could use a simpler outer join:
SELECT m.id_member AS id
, m.real_name
, a.value AS cust_armaus
, u.value AS cust_usermo
FROM smf_members m
LEFT
JOIN smf_themes a
ON a.member_id = m.member_id AND a.variable = 'cust_aramus'
LEFT
JOIN smf_themes u
ON u.member_id = m.member_id AND u.variable = 'cust_usermo'
ORDER BY m.id_member
With either of those queries, you could use code something like this:
$sql = "SELECT ...";
$rs = $mysqli->query($sql)
if (!$rs) {
// handle error
echo 'query failed: (' . $mysqli->errno . ') ' . $mysqli->error;
die;
}
// loop through rows returned
while ( $row = $rs->fetch_assoc() ) {
echo '<member id="' . htmlspecialchars($row['id']) . '"'
. ' nick="' . htmlspecialchars($row['real_name']) . '">'
. '<cust_aramus>' . htmlspecialchars($row['cust_aramus']) . '</cust_aramus>'
. '<cust_usermo>' . htmlspecialchars($row['cust_usermo']) . '</cust_usermo>' ;
}
<?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";
I'm attempting to select a query to use based on the number of rows returned by a test result.
$id = mysql_real_escape_string(htmlspecialchars($_POST['id']));
$result = "SELECT FROM Notifications WHERE UserID=$id";
$r = e_mysql_query($result);
$row = mysql_fetch_array($r);
$num_results = mysql_num_rows($result);
$result = '';
if ($num_results != 0) {
$result =
"SELECT U.UserID,U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U, Notifications N " .
" WHERE U.LocationID=0 " .
" AND N.UserID='$id'";
} else {
$result =
"SELECT UserID, FirstName, LastName," .
" DATE_FORMAT(BirthDate, '%m-%d-%Y') AS BirthDate " .
" FROM Users " .
" WHERE LocationID = 0 " .
" AND UserID ='$id'";
}
echo $result;
e_mysql_result($result); //Bastardized/homegrown PDO
if ($row = mysql_fetch_assoc($result)) {
$retValue['userInfo'] = $row;
...
I'm checking the Notifications table to see if the UserID exists there, if it doesn't it loads what does exist from the Users table, if it does, then it loads everything from the Notifications table.
I'm echoing out the $result and the proper statement is loaded, but it doesn't execute. When I run the concatenated query I get from the PHP preview, it returns just fine.
Before I had to if/else this, I was running the first query, loading everything from the Notifications table, and it was loading just fine. What am I missing?
You can do the whole thing with one query with a LEFT JOIN.
$query= "SELECT U.UserID, U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U " .
" LEFT JOIN Notifications N " .
" ON U.UserID = N.UserID " .
" WHERE U.UserID = '$id'";
You are missing execute a query with mysql_query() on all $result
Also change (query variable should be quoted) so change your all variables $id quoted
$result = "SELECT FROM Notifications WHERE UserID=$id";
to
$result = "SELECT FROM Notifications WHERE UserID='$id'";
$r = mysql_query($result);
Note :- mysql_* has been deprecated use mysqli_* or PDO
So I have to add a WHERE query to this plugin I'm using for a reporting feature on a WordPress site. I have no time to do anything but add in another column and filter by the values in that column as there is not that much data to manage each update. The default value for the column I added is zero but I'll add new entries to represent years new people are added. However, when I filter based on the column value the whole query breaks and doesn't show up. I have no idea why. Here is the section involving its set up query displaying results.
<?php
$sql = "SELECT COUNT(*) FROM " . $wpdb->prefix . "presidentsreport_breakdown WHERE list_id = " . $atts['list_id'];
$total_breakdowns = $wpdb->get_var($sql);
$sql = "SELECT p.person_id, p.name, p.notes, p.school_year, b.breakdown_id, b.name as breakdown, b.description as breakdown_description FROM " . $wpdb->prefix . "presidentsreport_person p INNER JOIN " . $wpdb->prefix . "presidentsreport_breakdown b ON b.breakdown_id = p.breakdown_id INNER JOIN " . $wpdb->prefix . "presidentsreport_list l ON l.list_id = b.list_id";
$clean_where = " WHERE l.list_id = " . $atts['list_id'];
$where = "";
if($search != ''){
$where = " AND (p.name LIKE %s)";
$arg = '%' . $search . '%';
$args = array($arg);
}
$where = $wpdb->prepare($where, $args);
$order = " ORDER BY b.sort_order, b.breakdown_id, p.sort_name, p.name, p.person_id";
$results = $wpdb->get_results($sql . $clean_where . $where . $order);
?>
If I add anything in the variable $where it breaks the whole query. So if I add
<?php
$where = " WHERE p.school_year <= 2011";
?>
or
<?php
$where = " WHERE p.school_year = 0";
?>
Nothing will show up, For the last example if the default value is 0 everything should show up regardless. Thanks in advance for reading through!
Don't add WHERE to your variable. It is already assigned in $clean_where
$clean_where = " WHERE l.list_id = " . $atts['list_id'];
Here ------------^
You need to concatenate your addition parameters to the $where variable:
$where .= " AND p.school_year <= 2011";
There's no need of WHERE in where!