PHP and MySQL - display contnet of column between certain numerical values - php

I'm new to MySQL and PHP but was wondering if someone could help me with a little project I'm doing for my boss.
I have a SQL database (MyDB) and a table in there (mytable) with two columns - the first column (index) is an auto-incrementing integer from 1-10, the second column (date) has different dates and timestamps in the format of Year-month-day time 2013-04-12 1326
I'm trying to create a simple PHP page that first gets the current date (easy enough) then looks at the table and shows the number of rows that fall within yesterday's date. For example, if I have 3 rows with 2013-04-11 XXXX and 2 rows with 2013-04-12 XXXX (and today is the 12th April 2013) the page will display 3. (The time is not important but we can't remove it from the table as it's auto created by one of the other staff's programs and he refuses to change it).
So far I've got my php page, done a connection to the DB and defined two variables:
$startdate = date('Y'."-".'n'."-".'d'." "."0000");
$enddate = date('Y'."-".'n'."-".'d'." "."2359");
As the timestamp doesn't matter I've gone for the min/max possible on the variables. I realise this will only give the current date, trying to work out how to get it to display the previous day as the date in the variable.
Now I'm trying to create a sql query that will count the number of rows where the date field falls within the startdate and enddate variables (-1 day) but not too sure where to start or how this would look. I then need to output this as a variable in PHP so I can echo it later in the page.
Anyone able to point me in the right direction? Hope any of this makes sense.

You could write a query with no params to do this (if its always just yesterday).
SELECT * FROM <table>
WHERE DATE_FORMAT(<date column>,'%j-%Y') = DATE_FORMAT(DATE_SUB(now(),INTERVAL 1 DAY), '%j-%Y');
Date functions in the where clause might not be super awesome performance wise

Related

How to select data by using range of dates in MySql query?

I have a problem related to MySQL query, I use WAMPServer.
I have data in database which have range of dates but when I select data for example
select * from CHD WHERE addtime>='2018-06-15' and addtime<='2018-06-21';
It displays data from '2018-06-15' to '2018-06-20', data of 2018-06-21 are not displayed even if I do
select * from CHD where addtime='2018-06-21';
is not working
Please anyone can help me
This assumes that your column is of type datetime.
The shorthand version of your date in the filter clause is assumed to be at midnight of the date. Your values that you are attempting to retrieve have times after midnight of that date. You either need to define a timestamp along with the date, or you need to filter by the day after for less than equal to or the day before for greater than equal

Deleting records from SQL table when date is exceeded

I'm currently developing a system to manage students that are on a report in school but I've fallen across a stumbling block. In my SQL table ('onreport')there is a field called 'duration' I want any records where the date stored stored in this row is passed to be deleted, I.e the report has expired.
<?php
include('connect.php'); //connect to the database
$today = new DateTime("now");
$f_today=$today->format('Y-m-d');
mysql_query('DELETE FROM onreport WHERE duration ==$f_today');
//print('$f_today')
?>
I realise that this may not be the most efficient method even if it did work but I was getting desperate! I know that the code is running because including the commented out print statement prints today's correct date in the same format as the format in the table.
The duration column is type 'date' and in the table it is displayed as yyyy-mm-dd
It seems that instead of comparing dates, you are comparing string, which is generally considered a bad practice. But since you didn't post your DB schema it is hard to tell.
However if you to want to remove every report posted before today, you can use pure SQL query assuming that the field duration is of DATE type:
DELETE FROM onreport WHERE TIMESTAMPDIFF(DAY,CURDATE(),duration)>0
This queries compare two dates : CURDATE() which is the current server time with the value of duration and return a result in number of days. If this value is greater than zero, the row is removed.

Month automatically increasing in phpmyadmin database table

Is there any way to increase a table field named month every month..or I should say to the latest month...Just need to update the month value..i.e. In, it should be 1
march 3
July 7
etc.
Help me.
Closest you'll get without manually inserting idate('m') with every new record and without using fancy mysql... is by using mysql default TIMESTAMP field. Check this out:
http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
But this a date so you'll need to use MONTH(Field) to get the month.

MySQL - Single DATETIME or Separate DATE and TIME Columns?

In my application I'm developing a functionality for creating "reminders".
A reminder has a date and a time. In my application, I have a form to create / edit reminders - this has two separate fields to input this information:
<input type="text" name="date"></input> <!-- datepicker plugin -->
<input type="text" name="time"></input> <!-- timepicker plugin -->
Now as a rule I have always used a DATETIME column whenever I have needed to store date/time, however this is the first time I'm having to store a user inputted date/time.
I figured it would be best to have seperate DATE and TIME columns, because it would be easier to insert / retrieve the data to / from my application. For example I won't have to combine the values from the two input fields to create a single value to insert in to the database. And likewise I won't have to split a single value in to two values to populate the form fields in edit mode.
But on the other hand won't it be easier to query the table if I used one column? What do you think?
You should build bottom-up (database at the bottom). Don't think about the application, just the database. Now, what makes sense at the database level. DateTime.
So you need to write extra code at the application level.
Please see it
Adding a Timepicker to jQuery UI Datepicker
http://trentrichardson.com/examples/timepicker/
convert your date time according to your mysql format and store it
$mydate = strtotime($_POST['date']);
$myfinaldate = date("d-m-y", $mydate);
$mytime = strtotime($_POST['time']);
$myfinaltime = date("H:i:s", $mytime);
Seperating columns is unlogical. You can use timestamp as datatype and you can use mktime function to parse date and time easily.
Doesn't it depends on the system you're creating.
If you want to store dates beyond 2038 I would store the datetime and time separate.
what if you are developing a reservation application and at one end you need to know on what date and at what time to schedule an appointment for a user, and at the other end, you need to match the user to a doctors schedule. You save the doctors schedule in a database and you need to know (amoung other things) when the doctor is available (on what days), and at what times. Let us forget about the on what days for a moment, and focus on the time shedule first...
You need to develop a programmable schedule so that if you know that the doctor works 6 months in a particular calendar year. (Jan - Jun), He or she may work (9-5 M,W,Fr), and (10-3 T,Th). Sat and Sunday the doctor is off. So you develop a table to hold the Daily time schedule with 2 columns to hold the daily starttime and daily end time for each day of the week. 14 columns in total and a primary and possibly secondary key. So now its time for some date arithmetic (This is where it gets hairy:-|...
You can say i your query: (mySQL)
Select such and such...
where form.theapptdatetime between doctorschedule_startime_tuesday and doctorschedule_endime_tuesday
and this will do a match to see if your datetime is within the date range of your doctorschedulestartime and endtime... but what if all you need is the time??
will the date arithmetic still work if the time value is stored as a datetime???
In other words if I have 01:00:00 as my doctorschedule_startime, is this a legitimate date value for my arithmetic to work, or will a date portion be forced upon me.
Perhaps I should store the time as a varchar, and convert it to a suitable datetime value and perform the arithmetic in the code instead of the query????
An example comes to my mind as to when have date and time split:
You could want to have DATE a part of the unique index, so that a user is only allowed to add 1 record to some table per date, but still you want to know the TIME he added it, so you keep DATE and TIME separate.

How to update/Insert random dates in SQL within a specified Date Range

Please forgive me. I am an absolute newbie and I need help with this table in phpmyadmin
My Table has the following columns:
Primary_ID, Begin_Date, End_Date, Timestamp
How do I update in phpmyadmin, selected rows with randomly generated begin_dates and timestamp within a specified date range (eg: 30 days in a month).
E.g of desired outcome
Primary_id--- Begin_Date -------------Timestamp
1.------------2008-09-02--------------2008-09-02 21:48:09
2.------------2008-09-03--------------2008-09-03 15:19:01
3.------------2008-09-14--------------2008-09-14 01:23:12
4.------------2008-09-27--------------2008-09-27 19:03:59
Date Range between 2008-09-01 and 2008-09-31.
Time is variable 24 hrs
I am a newbie, so a syntax that will work in phpmyadmin will help greatly.
We are making a presentation for a gym site with 500 members but the added member values all have the same begin date and time. Trying to separate them into different monthly registrations in the database, eg 50 people registered in August at different days and times, 35 people in October, etc. Hope it is clearer now. Thanks –
When I try one of the below answers, I get this error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '$randomDate = rand(1,31)' at line 1. So ideally, a code I can copy and paste into phpmyadmin with minimal editing will be appreciated. In sequence if possible. For a total dummy to understand and execute.
I'd start with something like this. A bunch of these can be combined, but I split it up so you can see what I'm doing.
To get random numbers, you can use rand(). Get one for the date, hour, minute, and second
$randomDate = rand(1,31);
$randomHour = rand(1,24);
$randomMinute = rand(0,59);
$randomSecond = rand(0,59);
You will want leading zeros (03 instead of 3) so you can use str_pad to add them, if required
$randomDate = str_pad($randomDate, 2, '0',STR_PAD_LEFT);
//The '2' is how many characters you want total
//The '0' is what will be added to the left if the value is short a character
Do the same with all your other random values.
Just because I like neat queries, you should make up your final update strings next.
$newDate = '2008-09-'.$randomDate;
$newTime = $randomHour.':'.$randomMinute.':'.$randomSecond;
Now I don't know how you're determining which rows you want to update, so I will leave that up to you. For an example, I will show you a query if you wanted to do this with Primary_id 3:
$x = mysql_query("UPDATE yourTable SET Begin_Date=\"$newDate\", Timestamp=\"$newTime\" WHERE Primary_id = 3");
something like:
insert into myTable (begin_date) values date_add('2008-09-01', INTERVAL RAND()*30 DAY)
that should create a new row with a random begin_date
update myTable set Timestamp = date_add(begin_date, INTERVAL RAND()*1440 MINUTE)
then that one should set the timestamp to a random minute of that day.

Categories