Using php DateTime object in mysql query - zend-framework

I'm trying to create a query that pulls information about sellers from my database, but only if their store has launched in the last 3 days. The easiest way I can think of to calculate the date for the query is using a new DateTime() object. When I output my code to test it, it's in the proper string for MySQL to query it with, but whenever I try to bind the variable, I get an error. I'm using Zend_Db to query, (PDO adapter)
action:
public function indexAction()
{
$dateMod = new DateTime();
$dateMod->modify('-2 days');
$dateMod->format('Y-m-d H:i:s');
// get sellers initialized in last 3 days
$sellerTable = new Application_Model_DbTable_Sellers();
$select = $sellerTable->select()->setIntegrityCheck(false);
$select->from(array('s' => 'seller'),array('sellerID', 'businessName'));
// select firstName, lastName, picture from user table, and businessName and sellerID from seller table.
$select->join(array('u' => 'user'), 's.userID = u.userID', array('firstName', 'lastName', 'picture'));
$select->where('s.active = 1 AND s.contentApproval = 1 AND s.paymentApproval = 1 AND s.featured = 1');
$select->where('s.launchDate > ?', $dateMod);
$select->order('s.launchDate DESC');
$newSellers = $sellerTable->fetchAll($select);
When I assign $dateMod to the view, it outputs the correct Y-m-d H:i:s format. But when I plug it into the query, I get the following error:
Message: SQLSTATE[42000]: Syntax error or access violation: 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 ') ORDER BY `b`.`launchDate` DESC' at line 2
If I hardcode a value into dateMod in the mysql timestamp format, the query works fine. How can I access just the string value of the timestamp in the DateTime object? getTimestamp returns a unix formatted timestamp, even after assigning a format.

The format() function returns the formatted date, so you need to assign that to a variable for use in the query:
$dateFormatted = $dateMod->format('Y-m-d H:i:s');
$select->where('s.launchDate > ?', $dateFormatted);

Related

.NET 6 : get database records by date except today's date EF Core?

I have a table in which the values ​​are recorded along with the date.
My date field is of string type:
"1401/09/23"
I want to get rows that date back to yesterday:
public async Task<List<Reservation>> GetReservations()
{
return await _context.Reservations.OrderByDescending(r => r.DateReserve).ToListAsync();
}
I also used the following code, but it gives an error!
return await _context.Reservations.Where(r => DateTime.Parse(r.DateReserve, CultureInfo.InvariantCulture) >= DateTime.Parse(DateConvertor.ToShamsi(), CultureInfo.InvariantCulture)).ToListAsync();
Error :
Assuming your code is correct functionally (I have no idea what a "Shamsi" is), you can fix your error by using ".AsEnumerable()":
return _context.Reservations.AsEnumerable().Where(r => DateTime.Parse(r.DateReserve, CultureInfo.InvariantCulture) >= DateTime.Parse(DateConvertor.ToShamsi(), CultureInfo.InvariantCulture)).ToList();
Please note that this means that your complete table will be pulled into memory of your PC and the statement will be executed by C# code on your PC, instead of a database statement on your database.

Using the Dart/Flutter Postgres Package to store dates and null dates needs two separate commands

I am using the Postgres Package (On the pub.dev site) to UPDATE records in a very simple database. It has two fields: a Text field prime key named number, and a Date field named date_of_birth.
If the date_of_birth is a valid DateTime string then all is well (as can be seen from the code below). But if date_of_birth is unknown (so I set to null) the UPDATE fails:
import 'package:postgres/postgres.dart';
void main() async {
final conn = PostgreSQLConnection(
'localhost',
XXXXX,
'XXXXX',
username: 'XXXXX',
password: 'XXXXX',
);
await conn.open();
DateTime dob = DateTime.now();
var results;
results = await conn.query('''
UPDATE account_details
SET date_of_birth = '$dob'
WHERE number = '123123'
''');
await conn.close();
}
If I set:
dob = null;
The program fails with the error:
Unhandled exception:
PostgreSQLSeverity.error 22007: invalid input syntax for type date: "null"
So I need to include a check on the dob field and the program now looks like this:
DateTime dob = DateTime.now();
dob = null;
var results;
if (dob == null) {
results = await conn.query('''
UPDATE account_details
SET date_of_birth = null
WHERE number = '123123'
''');
} else {
results = await conn.query('''
UPDATE account_details
SET date_of_birth = '$dob'
WHERE number = '123123'
''');
}
That works fine for my simple database, but in my real App. I have a number of date fields in one table. So I have to do a check for each possible combination of those date values - writing a code block for each!
Can anyone tell me how I can UPDATE both null and a valid date using a single statement please?
You are quoting the query parameters yourself. NEVER do this. In addition to the sort of problem you have just seen it also leaves you open to a trivial SQL injection attack.
The library you are using will have some way of putting placeholders into the query text and passing variables when executing the query. Use that.

Spring JPA: Find all records from the past or now

I have entity Ticket which has a field nextActionDate as Date/Timestamp.
I am heavily unclear how to select all records which are due to an update, i.e. is either now or in the past (with additional parameters).
In my JPARepository I want to annotate the method like
#Query("FROM Ticket t WHERE ... AND !t.nextActionDate.after(new Date())")
List<Ticket> findOpenedMail();
But this fails with expecting '=', found 't'. Also I am not sure if new Date() will be calculated at the time of query - or already pre-prepared when the Bean is created.
So, what is the correct syntax?
You can pass date parameter and use <, > operators in your query:
#Query("FROM Ticket t WHERE ... AND t.nextActionDate < :nextDate ")
List<Ticket> findOpenedMail(#Param("nextDate") Date nextDate);
and call yourRepository.findOpenedMail(new Date());
If you are using mysql you can try annother aproach by changing the date type to Long and save your date in seconds/milliseconds and use the mysql function UNIX_TIMESTAMP(NOW()) (now() is optional) in nativeQuery.
#Query(value = "select * from ticket t where... and t.next_action_date < UNIX_TIMESTAMP()", nativeQuery = true)
List<Ticket> findOpenedMail();
UNIX_TIMESTAMP() will return the current date in seconds.

Mirth Connect SQL Server Error : Conversion failed when converting date and/or time from character string

I am trying to insert into SQL Server DateTime field. Trying simple scenario of one table having datetime column named start_date only.
Query I am trying is
INSERT INTO test (start_date) values (${start_date})
start_date is channelMap variable of Type java.util.Date , It was created using :
var start_date = DateUtil.getDate('yyyyMMddHHmmss', msg['date'].toString());
Here start_date is of java.util.Date, why mirth treats it as String when it tries to insert into database ??
You can handle the conversion even in SQL. Hope it helps
var start_date = msg['PID']['PID.7']['PID.7.1'].toString(); // 19831123 - YYYYMMDD format
try {
sql="INSERT INTO test (start_date) values (convert(datetime,'" + start_date + "',5))";
logger.info(sql);
rst = dbConn.executeUpdate(sql);
}
catch(err) {
logger.info('ERR: ' + err);
}
Out in DB will be below.
select * from test
start_date |
----------
1983-11-23 00:00:00.000
2nd Approach
If you still want to use util try below
var start_date = msg['PID']['PID.7']['PID.7.1'].toString(); // 19831123 - YYYYMMDD format
/*
Input is yyyyMMdd and
output is yyyyMMddHHmmss format
*/
var datestring = DateUtil.convertDate('yyyyMMdd', 'yyyyMMddHHmmss', start_date);
try {
sql="INSERT INTO test (start_date) values ('" + start_date + "')";
logger.info(sql);
rst = dbConn.executeUpdate(sql);
}
catch(err) {
logger.info('ERR: ' + err);
}
I believe your data is inserting in DB as 'Mon Feb 19 09:25:16 IST 1968' along with quotes.
I used formatDate function, but data inserted into DB will be like 1968-02-19 09:25:16
var pidDate = msg['PID']['PID.7']['PID.7.1'].toString();
var value = DateUtil.getDate("yyyyMMddHHmmss",pidDate);
var data = DateUtil.formatDate("yyyyMMddHHmmss", value)
channelMap.put("start_date",data);
Inserting to DB:
var dateValue = $('start_date')
dbConn = DatabaseConnectionFactory.createDatabaseConnection(dbDriver, dbAddress, userName,passwd);
result = dbConn.executeUpdate("INSERT INTO test (startdate) values ('"+dateValue+"')");
I'm sending date value as 19680219092516,inside DB value is 1968-02-19 09:25:16.Datatype of my DB is DateTime type.
the getDate function returns a java.util.Date object, but when I tried with getCurrentDate function, it returns a formatted String. I guess formatting the date object is one way of inserting data into DB.

Trying to get month from date in laravel (and postgres extract not working)

I'm making my first laravel project, using postgres, and I'd like to be able to access all the people with a birthday this month (my people table has a birthdate field that's a date). I can use extract to get these records from the database, like so:
select * from people
where extract (month from birthdate) = 11;
But when I try a few different ways in my controller I get 'unknown column' errors:
$birthday_people = DB::table('people')
->where ("extract(month from birthdate)", "=", "11")
->get();
(I'll ultimately adjust it to compare with Carbon::now()->month, and use the model Person::all(), but until I get some results coming through I'm going as simple as possible)
Is there a special way to get the month from a date in laravel?
Update: I'm using a scope now in my Person model. I can get person results to come through when I give it an exact date:
public function scopeBirthdays($query)
{
return $query->where('birthdate', '=', '1947-11-02');
}
And I can get results back for month if I do it this way, but the catch is it doesn't seem to know it's a collection of People anymore (I can't access person columns when I display it out and I can't chain other scopes):
public function scopeBirthdays($query)
{
return $query->whereRaw('extract(month from birthdate) = ?', ['11'])->get();
}
Laravel's query builder offers 'whereMonth'- (seems the most right), but it gave me an 'undefined function' error until I put the bool on the end, and now the current error suggests that it's interpretting number of months instead of which one(?):
public function scopeBirthdays($query)
{
return $query->whereMonth('birthdate', '=', Carbon::today()->month, true);
}
I get:
Syntax error: 7 ERROR: syntax error at or near "month"
LINE 1: select * from "people" where 1 month("birthdate") = $1
^ (SQL: select * from "people" where 1 month("birthdate") = 11)
Final update: I was able to get results back (that were correctly interpretted as people) by using whereRaw in my scope:
public function scopeBirthdays($query)
{
return $query->whereRaw('extract(month from birthdate) = ?', [Carbon::today()->month])->orderBy ('birthdate', 'asc');
}
Thanks, everyone!
based on previous question try:
$birthday_people = DB::table('people')
->whereRaw("extract(month from birthdate)", "=", "11")
->get();
You can set is as relationship
public function custom(){
return $this->hasMany('App\Models\People')->whereRaw("extract(month from birthdate)", "=", "11");
}
You could try something like this. It will return as an instance of App\People so you will be able to use your eloquent functions still.
public function scopeBirthdays($query)
{
return $query->where('birthdate', 'LIKE', Carbon::today()->year . '-'.Carbon::today()->month.'%');
}
I don't have much experience with Carbon, I'm assuming that Carbon::today() will return an object with the year, month, and date.