I need some advise on implementing my database schema properly. I have a cron script whose main functions are to Parse HTML docs => Create a DB tbl => Insert Records
I am used to run this script only once per month but I need to do it more frequently which means my database tables will increase significantly. At the moment my tables follow this format : table_03 where the last two digits represent the current month.
Now I am considering using PHP time() function to replace the current month.
My first question, is this a good way to approach it ?
My second issue is how do you go about creating a dynamic SELECT statement that fetches the last two tables in a Database based on their date ? or could be better to know if there is an MySQL query that does this job instead of relying of the table names ?
e.g
table_29_03 // 29 March
table_26_03 // 26 Mar...
table_25_03
...
My query should return the difference between the last two or three table, but not having consistent dates ( as monthly ) I am not sure how to do it.
At the moment I am doing the following :
$thisMonth = 'table_'.date('m');
$PrevMonth = 'table_'.date('m', strtotime('first day of last month'));
// find new records in this table not available in previous one
$sql = "
SELECT * FROM `".$thisMonth."` WHERE `".$thisMonth."`.`id`
NOT IN (
SELECT `".$PrevMonth."`.`id`
FROM `".$PrevMonth."`
WHERE `".$thisMonth."`.`id` = `".$PrevMonth."`.`id`
); ";
My second issue is how do you go about creating a dynamic SELECT statement that fetches the last two tables in a Database based on their date ?
is this what you want to achieve in MySQL?
SELECT create_time,table_name
FROM INFORMATION_SCHEMA.TABLES
ORDER BY create_time DESC LIMIT 2
you can add additional filters like what schema should we extract the data from, etc...
As for your first question, I am using gmdate as of now to extract the month and year of time.
$now = time();
$month = gmdate("m", $now);
$year = gmdate("y", $now);
gmdate: time returned is in Greenwich Mean Time (GMT).
using time(); to set your month is alright and i can see no problem in that.
Side Note: If you are running PHP and MySQL on separate machines, there would be some discrepancies in time if the datetime of those two are not synced. if you want an accurate time representation of both. You should be dependent on one machine.
If you want PHP to handle time logging, you can include a column in in your tables like 'created_at' which indicates the time when it was generated, based on PHP time();
If you want MySQL to handle it, you can query first the current date
select curdate();
then create the table names based on the month you fetched from your query.
Related
I have a MySQL database with some columns and in two of them I have two different dates.
In the site I have the two dates in a two colums inside a table, but I need to calculate and reproduce in another column the number of days between that two dates.
I found this code:
?php
$date1 = date_create("2017-04-15");
$date2 = date_create("2017-05-18");
//difference between two dates
$diff = date_diff($date1,$date2);
//count days
echo 'Days Count - '.$diff->format("%a");
?
And it works but I need to change this dates and put the data inside my database. Jow can I solve this?
Im using this:
update client_invoices
set x6 = datediff(x4, date_due)
as an event in mysql but everytime they updates the server the "Event scheduler status" is turned off.
How can i perform this directly in my sql without scheduling events?
Thanks,
Ribas
In MySQL, you would simply use datediff():
select t.*, datediff(day1, day2) as days_diff
from t;
If you want to update a column:
update t
set diff = datediff(day1, day2);
I have tons of records that are in my database table leadactivity basically I need to display all the records that were created in the first week of the current month, then also another query to display records in the second week, same for third week and then finally the fourth week of the current month.
I have a column called created_date which onupdate puts in the current timestamp
What is the best way to achieve this?
You can use date functions for this:
select la.*
from leadactivity la
where day(la.created_date) between 1 and 7 and
created_date >= curdate() + (1 - day(curdate())) day;
The above assumes MySQL syntax. Most databases have similar functionality, although the specific functions may differ.
I have a PHP scirpt that is always querying all the data from a database table and it's getting pretty slow. I really just need the data of a specific month and year.
Is there a simple way to get only those entries? For example, everything from February 2013?
The column that stores the dates in my table is of type datetime, if that applies to the solution.
You can add that condition in the WHERE clause of your select statement. I would recommend using BETWEEN operand for two dates:
SELECT myColumns
FROM myTable
WHERE dateColumn BETWEEN '2013-02-01' AND '2013-02-28';
If you mean to say you want everything beginning with February 2013, you can do so using the greater than or equal to operator:
SELECT myColumns
FROM myTable
WHERE dateColumn >= '2013-02-01';
EDIT
While the above are my preferred methods, I would like to add for completeness that MySQL also offers functions for grabbing specific parts of a date. If you wanted to create a paramaterized query where you could pass in the month and year as integers (instead of a start and end date) you could adjust your query like this:
SELECT myColumns
FROM myTable
WHERE MONTH(dateColumn) = 2 AND YEAR(dateColumn) = 2013;
Here is a whole bunch of helpful date and time functions.
You should index the datetime field for added efficiency and then use Between syntax in your sql. This will allow the mysql engine to remove all records that you are not interested in from the returned data set.
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
I have a database, that was an initial dump of an Excel file via phpmyadmin. So no formatting or other logic was applied to the table. So I am essentially left with a table of "varchar" style rows. Of which include things like dates and times.
Example:
start_time, end_time, start_date, end_date .. which look like 7:30 PM, 11:00PM, 9/9/12, 11/22/12 and then some rows that are fine just the way they are. Unfortunately I can't convert the whole table to a better format as someone based a lot of functionality around this lousy design of whats called a table. The only thing truely going for it, is the table has an auto incremented ID for each row that I can associate with something. So I figure as a means of Patching things up while we fix a lot of this functionality that strips things apart and all else I could make a bridge of sorts.
Make a table that can have proper types of rows for the data types, and then be able to use some mysql functionality like BETWEEN() for example on start_date to get a listing of a - z but a limited listing.
So I am trying to figure out is there a way I can dump data from one table to the next but in the process of this query have it convert it over to the types I want such as datetime, combining start_date and start_time into a datetime format and likewise with the end times/dates?
Or is this something I am going to have to pull out in a heap, loop over it with PHP and have it insert new rows into the new table?
I would do that with a PHP script to read the original data and then process it into the correct date formats, then insert to the new table.
So the scenario is, you have a time and date separated and you want to combine them, then format them to the DB acceptable date format. I would do something like this:
date_default_timezone_set('America/Los_Angeles');
// you have separate dates and times like this
$date = '9/9/12';
$time = '11:00 PM';
// combine them into one string
$str = $date . ' ' . $time;
$dt = DateTime::createFromFormat('n/j/y g:i A', $str);
$DBFormat = $dt->format('Y-m-d H:i:s');
echo $DBFormat;
// outputs DB date format -> 2012-09-09 23:00:00
One thing I noticed was your first time example was 7:30 PM and the next example was 11:00PM. In the latter example, there is no space before the PM. I don't know if that is a typo on your part or if your data does vary like that, if it does then I would add a check and insert the space.
For this, you can follow the steps:
Create a new table in the same DB which have all the fields in the source table(the table that going to copy).
Create a PHP file.
write a MYSQL query to select all the values in the source table.
In the while loop, write a query to insert these rows into the new table.
before that convert the value of start_time, end_time, start_date, end_date columns to the required format using "strtotime() and date()" functions in php.
insert the new values in the new table.