Add values from same date - php

I just got started learning PHP so if there's already an answer to this question, please point me to it as I wasn't able to find one.
I have a mysqli database with 2 entries: date_added & menu_price. The user inputs (through a webpage interface) the menu_price (double) while the date is automatically set in this format: Y-m-d. Note that multiple entries for menu_price can be set for the same date.
My question: I'm trying to pull out a daily report which should add all prices for every day and only display the date once.
Example: let's say I had two entries for 2015-04-10: 10 & 20 and I had 3 entries for 2015-04-11: 10, 20 & 30. So my report for 2015-04-10 should say 30 and for 2015-04-11 should say 60.
I managed to extract unique date entries (I'm not sure it's useful or not) the way described below but I'm not sure how to proceed.
// Extract unique date entries
$newDate = "SELECT DISTINCT (date_added) AS date_added
FROM main
ORDER BY date_added DESC";
$dateResult = $conn->query($newDate);
// Create an array with unique dates
$results = array();
while ($dateArray = $dateResult->fetch_assoc())
{
$results[] = $dateArray["date_added"];
};

This requires aggregate functions. Use SUM() and GROUP BY in your query:
$newDate = "SELECT date_added,
SUM(menu_price )
FROM main
GROUP BY date_added
ORDER BY date_added DESC";

Related

select stored mysql date and current date and compare it in months

Actually i am creating recruitment portal in which the candidate cannot apply again in 3 months. After 3 months he/she can apply. so i need to know how to do this. when candidate fill up form, the form date is stored in mysql database using current time stamp. now i need to compare the current time and database time, if difference between both date is greater than 3 months then only values can be added to the database.
In short the candidate cannot fill the form again in between 3 months. if the 3 months are completed then candidate can fill the form.
Suppose, in your database :
table name : candidates
fields : email, form_date, .... ( other fields )
where 'email' is the primary key and 'form_date' has the timestamp in which a candidate had filled the form last time successfully.
Then in your model : ( seeing your tag, I'm guessing you are using Codeigniter 3 )
$query = "SELECT email FROM candidates WHERE form_date < NOW() - INTERVAL 3 MONTH";
$queryResult = $this->db->query($query);
foreach( $queryResult->result() as $row )
$candidates_email = $row;
Now, you have the primary key in $candidates_email, you can update the candidate row with new information or do whatever you like :)
You can do some 'date math' in MySQL if you prefer. You didn't tell us what your table looks like but here's an example: SELECT ...., DATE_SUB(your_date_var, INTERVAL 3 MONTH) as SomeColName from YourTable WHERE.... So you can play around with this - and there's a DATE_ADD if you want to read their last apply day and add 3 months to it and compare to NOW(). Good luck.

PHP/MySQL - Calculate Total for each Reservation

I've got a Reservation application, and I'd like to calculate the total number of meals needed by reservations date span.
My database has fields:
$name - Person reserving
$chkin - Check in date (DATE yyyy-mm-dd)
$chkout - Check out date (DATE yyyy-mm-dd)
$guests - Number of people in group
$meal - Eating meals (Yes/No)
So for each reservation I have:
// Days of Stay
$days = (strtotime($chkout) - strtotime($chkin)) / (60 * 60 * 24);
What I'm not sure of is how to do the calculation for each reservation in the database.
My calculation for each reservation would be something like:
$days * $guests
I would appreciate advice on this query... I'm trying to give a snapshot of how many meals will be need to be prepared for a given month, weeekend, etc.
Thank you!
Something like this:-
SELECT SUM(guests * DATEDIFF(IF(chkin < $start_range, $start_range, chkin), IF(chkout > $end_range, $end_range, chkout)))
FROM sometable
WHERE chkin < $end_range
AND chkout > $start_range
AND meal = 'Yes'
Uses DATEDIFF() to get the number of days between the check in date (or if later the start of the date range you are interested in) and the check out date (or if earlier the end of the date range you are interested in) where meal is 'yes' and multiplies that by the number of guests, then uses SUM() to add them up for all bookings.
You can use the MYSQL date diff to achieve a count of the days, then this can be multiplied by the number of guests. Finally you will need to select a date range for this search. Below are the basics or the MYSQL needed in order to get these values. This should put you on the right track to achieving what you want.
SELECT DATEDIFF(a.chkout,a.chkin) * a.guests as meals
FROM table as a
WHERE a.chkin > '0000-00-00' AND a.chkout < '0000-00-00
I have tested this with a table of mine and it appears to be working correctly, however, without much data I can only test lightly. If you have any issues, leave a comment and I will try to help further.
http://www.w3schools.com/sql/func_datediff.asp
I'll give you a snippet as a starting point.
Let's say you want the top 10 guests with the longest stay.
SELECT DATEDIFF(chkout, chkin) AS daysstaying FROM reservations ORDER BY daysstaying DESC LIMIT 10
You can do calculations in queries and use the AS operator to create an alias for the result. I'm leaving it to you to work out the specific query you need to obtain the results you need.
I would also suggest that you investigate using views if this query needs to be used often.
http://dev.mysql.com/doc/refman/5.5/en/views.html
I was able to use Kickstart's and Erik's reply to come up with a solution! Thanks!!
// Get Current Month
$current_month = date('F');
// Current timestamp is assumed, so these find first and last day of THIS month
$start_range = date('Y-m-01'); // hard-coded '01' for first day
$end_range = date('Y-m-t');
$sql = "SELECT SUM(DATEDIFF(a.chkout,a.chkin) * a.guests) AS meals
FROM reservations AS a
WHERE a.chkin > '$start_range' AND a.chkout < '$end_range'
AND meal = 'Yes' AND confirm = 'Yes'";
No I will work towards forecasting for upcoming months as well!

selecting and displaying rows from different date values

I want to get rows from a table based on different dates. Although values of the dates are not always the same.
Basically I have to get first what are the range of the dates and then extract the rows of the columns based on those dates.
I cant do SELECT COUNT(location) FROM tweets WHERE date<= NOW() or date<=2012-07-29 17:38:32
cause as I said dates are not fixed. I DON'T PUT THE DATES but they are dynamically created.
Well, the crux of this is how the dates are generated but the query is simple:
$start = '2012-6-24';
$end = '2012-7-24';
"SELECT COUNT(location) FROM tweets WHERE date between '$start' and '$end'";

how to show one record per day order by id?

I have this little script that shows one wisdom each day.
so I have three columns.
Id wisdom timestamp
1 wisdon 1 4/1/2012
2 wisdon 2 4/1/2012
3 wisdon 3 4/2/2012
and I want to fetch array of one wisdom for each day
I looked around your website, but unfortunately I didn't find something similar to what I want.
also I got this code
$sql = mysql_query("SELECT DISTINCT id FROM day_table group by timestamp");
but this also not working.
any ideas?
is it possible to make a counter of 24 hours update wisdom date?
please give me some help.
You can make another table that is called wisdom_of_day
The table would have the following columns, id, wisdom_id, date
Basically each day you can randomly select a wisdom from your wisdom table and insert it into the wisdom day table. You can also add a constraint to your date column so it is distinct. It is important that it is a date column and not a timestamp since you don't care about time.
Then you can retrieve the wisdom of the day by querying based on the date.
It's possible I read your question wrong and you just want to select one wisdom for each day, but you want to show multiple days and you want to get the data from your table.
If so, the reason your query is not working is because you are grouping by a timestamp which includes the date and time. You need to group it by date for it to group like you want.
Here is a query that will group by the day correctly. This will only work if you have a timestamp field and are not storing a unix timstamp on an int column.
select id, wisdom, date(timestamp) date_only from day_table group by date_only order by date_only asc;
Hmm, I noticed that your timestamp values are in some kind of date format, maybe as a string? If so the above query probably won't work.
First compute number of days since 1970
SELECT DATEDIFF(CURDATE(), '1970-01-01')
Then insert this number inside RAND, for example:
SELECT * FROM table ORDER BY RAND(15767) LIMIT 1;
Rand with number as argument is deterministic.
Full query:
SELECT * FROM table ORDER BY RAND((SELECT DATEDIFF(CURDATE(), '1970-01-01'))) LIMIT 1;

Group and manipulate based on multiple columns

I have a table that inserts a row when a certain function is used on the site and stamps the date.
code-/----date----/--type
-----/------------/------
--1--/--2012-2-1--/-used
--1--/--2012-2-3--/-saved
--1--/--2012-1-3--/-printed
--2--/--2012-2-1--/-used
--2--/--2012-2-2--/-printed
I have to report the number of times code 1 was (printed or saved or used) today, or yesterday, or last month (date range)
I am starting with this:
$stat_query = mysql_query("SELECT code, type, date FROM tracking WHERE code IN ('$htL','$htG','$htR') GROUP BY code, type, date");
I use the IN operand because each user has 3 codes to track with limitless date entries for each type.
I really am lost as to what to do here.
You'll need to construct the date ranges and modify the query. Below is an example of showing the count for code in the past day:
SELECT `code`, COUNT(`code`) as code_cnt
FROM tracking
WHERE
`code` IN ('$htL','$htG','$htR') AND
`date` BETWEEN DATE_SUB(now(), INTERVAL 1 HOUR) AND now()
GROUP BY `code`
Check out the DATE_SUB documentation for further help
GROUP BY code, type, date in this example makes it to return only one record. Because all code rows would be summerized in distinct output row, also type would be reduce more and more. Please check your GROUP BY fields.

Categories