How to use INTERVAL in CakePHP 3.x - cakephp

I am using CakePHP 3.x. I have converted and stored all my dates to string using the strtotime(date('Y/m/d h:i', time())); .And in DB it will store like this 1479466560 But Right now i need to select rows from exactly 14 days ago. I tried like below conditions,
$this->loadModel('Users');
$userList = $this->Users->find('all')
->select(['created'])
->where(['status' => 1,'created' => 'created + INTERVAL 14 DAY > NOW()']);
It is returning empty rows only. How to do this ?. Can any one help me !

I know this does not tell you how to use interval but it does solve the problem.
What I've done in the past is a simple >= < combination together with php variables:
$cur_date = date_create();
$date = clone $cur_date;
$date->modify("-12 hours");
$this->Model->find()
->where(['created >= ' => $date])
->andWhere(['created < '=> $cur_date]);
This effectively uses an interval. It is also nicely dynamically editable.

Your query doesn't match with any created date from your users table.
Your CakePHP3 query generated below SQL:
SELECT created FROM users WHERE (status = 1 AND created = created + INTERVAL 14 DAY > NOW())
Note: At First try and adjust above query from your phpmyadmin.
You can try below SQL for INTERVAL test
SELECT '2016-01-17 10:57:21' + INTERVAL 14 DAY > NOW();
OR
SELECT '2016-01-17 10:57:21' + INTERVAL 14 DAY;
Note: Adjust date string as you need. Now you can see what is the wrong you have done

Related

Is there a faster way to get data from a SQL Server database with Python?

I am newbie software developer and I am trying to improve system for reports which I am using.
Problem is, I have data in a SQL Server table, with a few million rows and 10-15 columns.
Devices are sending data every 20 seconds to the database with datetime, deviceid, value and some other things.
This is how I tried to solved this problem with Python:
while plus_10 < endTime:
query= 'SELECT TOP 1 [DateTime],[Value] FROM [tblName] WHERE [DeviceId] = {0} and [DateTime] >= \'{1}\''.format(device,plus_10)
df1 = pd.read_sql_query(query, conn)
if not df1.empty:
date = (df1.iloc[0]['DateTime'])
value = (df1.iloc[0]['Value'])
colA = 'A{0}'.format(counter)
colB= 'B{0}'.format(counter)
sheet[colA] = date
sheet[colA].alignment = alg2
sheet[colA].border = brd
sheet[colB] = value
sheet[colB].alignment = alg3
sheet[colB].border = brd
counter += 1
plus_10 = date + timedelta(minutes = 10)
So, I have a while loop and query inside it. I am looking for TOP 1 time, and after I report to Excel, I am increasing last time for 10 minutes. When my current time (plus_10) is higher that endTime (15:00), the report will be done.
With this way, my program is working, but problem is time taken to generate the report. It takes 20-30 seconds every time I call the query because the database has a few million rows (can't be lower!) and I'm searching by datetime.
From 08:00 - 15:00 it takes over 20 minutes to generate.
Can I somehow improve my query or maybe something in my python code? I know that searching million rows by datetime is slower than search by ID, but I do not know how to solve this.
Thanks in advance for help. :=)

How to match a specific string inside a string fetched from database in MVC 5?

So I am building a project where I need to fetch date from the database and on the basis of the given month,
as I need to find customers who have birthday on the given month. I have a query that works perfectly fine in the SQL server but I don't get its equivalent in Linq.
So here is my query that runs in SQL
SELECT * FROM CustReg
WHERE DOB LIKE '_____month%'
I need to match that month as it should come in the 6th position of that DOB string.
Demo Database-
Id Name DOB
1 AB 1995-02-20
2 CD 1998-04-13
4 EF 1991-02-15
5 GH 1988-06-8
6 IJ 2000-02-09
Query - Select all Employee whose birthday comes on feb.
Expected Output - AB,EF,IJ.
PS- I have taken datatype of DOB string not Date or DateTime.
I also have month in string (for eg '02' for feb)that I have fetched from the input date.
If I have understood your question right, may be the following code helps.
First create a enum of Months,
public enum Month
{
Jan=1,Feb,Mar,Apr,May,Jun,July,Aug,Sep,Oct,Nov,Dec
}
Now use the following query to get what u wanted,
Month requiredMonth = Month.Feb;
var res = CustReg.Where(x => (Month)Enum.Parse(typeof(Month), x.DOB.Substring(5, 2)) == requiredMonth).Select(x => x.Name);
foreach (var item in res)
{
Console.WriteLine(item);
}

sending reminder mail when specific no. of days are left Which is manger by the Query SQL Server?

i want to send the Email on Certification expiry when 21,14,7,3,2,1 days are left by a scheduler which picks the data by the Query .
i am using the ExpiryNotification bit col.as a flag(as previous it used to sent on 30 days only)
the data in the Query is picked from scheduler.now if i have to do changes in the Query to implement this logic i will need to change the col from bit to int and check the Notification col.but what if the Scheduler does not run when 21 days are left for some odd reason then what will happen.is there any other way to implement this Logic by sql server ?
it will make the ExpiryNotification col value to 1 when the mail is send
exisitng Query (checking only 30 days)
Select * from wsm_certification
where
(DATEDIFF(d, GETDATE(), wsm_Certification.RenewalDate) = 30
and wsm_Certification.ExpiryNotification = 0)
You may try something like this
(DATEDIFF(d, GETDATE(), wsm_Certification.RenewalDate) = 21 OR (DATEDIFF(d, GETDATE(), wsm_Certification.RenewalDate) = 14
Use in operator to check multi values
Eg:
Select * from wsm_certification
where
(DATEDIFF(d, GETDATE(), wsm_Certification.RenewalDate) in (21,14,7,3,2,1)
and wsm_Certification.ExpiryNotification = 0)

Codename One Database print range of rows

I am using Codename One to get data from a database and display it in a table.
This is functioning quite well, and now I am trying to add a feature that limits the number of items that are shown in the table. To get there, I want to retrieve a selected number of columns from the database .
Unfortunately, common java sql operations do not seem to work. Below is what I have so far. All approaches don't throw any errors, but also also don't display the desired range or ranges. Another way to obtain a selection would probably be an ArrayList, but I would very much like to stick with a direct approach, since this appears to be relatively easy and elegant solution.
db = display.getInstance().openOrCreate("MyDB.db");
db.execute("CREATE TABLE IF NOT EXISTS Termine (Date NOT NULL,Event NOT NULL, Date_String NOT NULL)");
// prints the entire number of items from the database
cur = db.executeQuery("select * from (select * from Termine order by Date) where Date >= 5;");
// doesn't print anything
cur = db.executeQuery("SELECT * from ( select m.*, Date r from Termine m ) where r > 4 and r < 10;");
// doesn't print anything
cur = db.executeQuery("SELECT * from ( select m.*, Date r from Termine m ) where r BETWEEN 5 AND 10;");
while (cur.next()) {
Row currentRow = cur.getRow();
String event = currentRow.getString(1);
System.out.println(event);
}
Is my approach feasible? Any help would be greatly appreciated.
You can use the LIMIT SQL keyword as explained here.
SELECT column_list FROM table LIMIT row_count OFFSET offset;
A good practice is to search for "sqlite" and the SQL feature you are looking for as mobile SQL databases on all platforms are based on sqlite which has some quirks.

Query Drupal User Table for: date created < $today - '100000'

I would like to select users from the Drupal users table where the date created was older than 1 day ago. Then delete those users. This code isn't correct but it will give you an idea of what I am trying to do I just don't know the right DB query.
'
$users = db_select('user', 'created') //I know this is not the right DB query
$count = count($users);
if($count > 0){
$users = user_load_multiple(array_keys($users['user']));
}
$today = getdate();
if ($users < $today - '100000' ) {
user_delete($user->uid)
}
I am thinking about using user_load_multiple() to load the users in to an array to perform the delete action.
Get an array with the uids of the users you want to delete and use user_delete_multiple($arrayOfUidToDelete) : https://api.drupal.org/api/drupal/modules!user!user.module/function/user_delete_multiple/7
Using the function user_load_multiple() can be heavy on ressources if you have a lot of users and you will end with PHP errors (out of memory...).
Plus you don't need to load the users, you just want to delete them.
For the query I will go with db_query instead of db_select if there is no parameters valued by an user (better performances).
So it will look something like :
//get the list of uid
$user_list = db_query("select uid
from users
where CAST(FROM_UNIXTIME(created) as date) < NOW() - INTERVAL 1 DAY"
)->fetchCol();
// delete the users
user_delete_multiple($user_list);

Resources