PHP date() function inserting zeros into database - php

I have an array like so which has the column names of the table on the left and the associating values on the right.
$proceduredata = array
(
'patient_id' => $patientfk,
'name_id' => $procedurenamefk,
'department_id' => $departmentfk,
'dosage_id' => $dosagefk,
'edocument' => NULL, //not implemented yet
'user_id' => $this->session->userdata('userID'),
'duration' => NULL, //not implemented yet
'submitted' => date('d-m-Y H:i:s', now()),
'comment' => NULL, //to be implemented
);
This array is then passed into a SQL insert function. The insert works fine but my "Submitted" column is getting values of this only:
0000-00-00 00:00:00
I made sure the time formats are matching? Is there something I have missed thanks.

change the date format
submitted' => date('Y-m-d H:i:s', now())

I believe that the "now()" function is a sql function and you are using PHP with the "date()" funciton. Try changing "now()" to "time()" which will give you a proper unix timestamp that the "date()" function can use to create a properly formatted date.
EDIT: I just realized I am not familiar with codeignighter, so please excuse me if the "now()" function is part of that framework.

now() is not a function, change now() to time(). Alternatively, date()'s second paramater is optional if you omit it date automatically uses the current date/time:
echo date('d-m-Y H:i:s');
will echo the current date/time in the format requested.

Related

Laravel set date as 1970 when the value is null

Sometimes laravel set date 1970 when the value is null, it's possibile save value as NULL instead 01-01-1970?
'start_date' => date('Y-m-d', strtotime($request->input('start_date'))),
'end_date' => $request->has('end_date') ? date('Y-m-d', strtotime($request->input('end_date'))) : NULL,
This code is not working.
How i can solve it?
According to this answer In Laravel 5.5+
$request->exists: Alias for $request->has
$request->has: Determine if the request contains a given input item
key.
$request->filled: Determine if the request contains a non-empty value
for an input item.
All you need - change has to filled:
'end_date' => $request->filled('end_date') ? date('Y-m-d H:i:s', strtotime($request->input('end_date'))) : NULL,
In MySQL if the date format is not complete or invalid it is set to the default.
Update your date function to include time, if you have a datetime field you must also pass a time.
date("Y-m-d H:i:s");
'start_date' => date('Y-m-d H:i:s', strtotime($request->input('start_date'))),
'end_date' => $request->has('end_date') ? date('Y-m-d H:i:s', strtotime($request->input('end_date'))) : NULL,
Please try the below code
Need to check whether request has available then convert to time
'start_date' =>$request->has('start_date') ? date('Y-m-d', strtotime($request->input('start_date'))) : NULL,
'end_date' => $request->has('end_date') ? date('Y-m-d', strtotime($request->input('end_date'))) : NULL,

Why does mysql ceil datetime strings?

I'm having a problem when searching a datetime column with a string.
I'm using codeigniters insert_batch, but I'm sure it's the same if I use insert. This is an example of the data I'm inserting:
$valor_log_proceso = array(
'id_interno' => 21656,
'proceso_id' => 1,
'fecha_inicio' => '2015-12-02T09:04:59.884',
'fecha_fin' => '2015-12-02T09:20:10.884',
'equipo' => "EQUIPOPC",
'usuario_id' => 2,
'log_envio_id' => 10
);
In the mysql db 'fecha_inicio' and 'fecha_fin' are datetime colmuns.
'fecha_inicio' and 'fecha_fin' values in every single $valor_log_proceso array are strings retrieved from a request.
When I try to look for that data with a get_where
$valor_log_proceso = array(
'id_interno' => 21656,
'proceso_id' => 1,
'fecha_inicio' => '2015-12-02T09:04:59.884',
'fecha_fin' => '2015-12-02T09:20:10.884',
'equipo' => "EQUIPOPC",
'usuario_id' => 2
);
$result = $this->db->get_where($table_name, $valor_log_proceso)->result_array();
$result is an empty array.
Then I check the database and see that the dates where truncated/ceiled to:
fecha_inicio: 2015-12-02 09:05:00
fecha_fin: 2015-12-02 09:20:11
So the question is why does that happen?
How can I search correctly for rows in the table?
The reason this is happening is that a DATETIME column can only have this pattern of data. As you see, it is stripping out the 'T' as well.
See https://dev.mysql.com/doc/refman/5.6/en/datetime.html
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
In order to create the query correctly, you will have to change your array to match the same pattern...
'fecha_inicio' => '2015-12-02 09:04:59',
'fecha_fin' => '2015-12-02 09:20:10',
ADDITION
Here is a function to manipulate the current format to the needed format
function format($x){
$x = preg_replace('/[T]/', ' ', $x);
$y = explode(".", $x);
return $y[0];
}
$x = format('2015-12-02T09:04:59.884');
echo $x; // Prints 2015-12-02 09:04:59

CakePHP: How to change default value of Date input

I am trying to make a date input that defaults to the value that is already in the database.
However, when I set the month, year, and date to the database values, the month, date, and year attributes are set on the select element but the page still displays the current date as the default values. When the form is submitted, today's date is stored in the database.
Heres the code:
$mail_date_time = \explode(" ",$campaign["MailedDate"]);
$mail_date = explode("-",$mail_date_time[0]);
echo $this->Form->create("Campaign");
echo $this->Form->input("MailedDate",array(
'month' =>strtotime($mail_date[1]),
'year' => strtotime($mail_date[0]),
'day' => strtotime($mail_date[2])
));
echo $this->Form->end("Submit");
$mailed_date turns out to be: [0]=2009 [1]=11 [2]=11
Does anyone know how to solve this?
Thanks!
The Cake form helper includes formatting of dates... i.e. 'dateFormat' => 'DMY' in your MailedDate input.
The value displayed by the input field would default to the value contained in $this->data and can be overwritten completely using 'default' => 'value', or prefilled using 'empty' => 'value'.
In order to precompile the datetime fields is necessary to use the 'default' keyword:
$mydate = '2015-09-10 06:40:00'
echo $this->Form->input('datetime', array(
'label' => 'Date 2',
'default' => $mydate
));

Building an Array with a NOW() command for datetime

OK I have a mySQL table that has a few date columns in, it is set up so that there is a create date and a update date. The UpdateTimeStamp column updates automatically using the on update CURRENT_TIMESTAMP Attributes,
Its my understanding that you can only use a one timestamp in this special way, and this is fine.
So on the createdate column I need to manually add the date that the record was created its a datetime column.
I have read that you can use the NOW() command for this. However using it in the following brings me a undefined function error. I have tried it as just 'CreateDate' => NOW(), which gives the same error or using 'CreateDate' => set_value('NOW()'), does not produce an error but no value is entered into the database for this column.
form_data = array(
'ClientID' => set_value('ClientID'),
'ClientReference' => set_value('ClientReference'),
'CreateDate' => set_value(NOW()),
'Gender' => set_value('Gender'),
'MaritalStatus' => set_value('MaritalStatus'),
'ContactNumber' => set_value('ContactNumber'),
'Nationality' => set_value('Nationality'),
'Ethnicity' => set_value('Ethnicity'),
'ClientNotes' => set_value('ClientNotes')
);
I Have tried all the answers you have provided and its still not working its letting me add to the database but the CreateDate value is 0000-00-00 00-00-00
If your mysql column type DATETIME:
'CreateDate' => set_value(date('Y-m-d H:i:s'))
if TIMESTAMP:
'CreateDate' => set_value(time())
You can have both set automatically on insert and update.
Use a default value of CURRENT_TIMESTAMP on "CreateDate" so it sets automatically when you create the record, and a trigger to update "UpdateTimeStamp" when the row is altered
CREATE TABLE Clients (
ClientID INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
/* Other Columns */
CreateDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UpdateTimeStamp TIMESTAMP NULL
) ENGINE=InnoDB;
CREATE TRIGGER ClientsUpdate
BEFORE UPDATE ON Clients FOR EACH ROW
SET NEW.UpdateTimeStamp = NOW();
There is no now() function in PHP, what you are looking for is the time() function. However, this will return a timestamp such as 1370183405.
MySql has a now() function in which case you need to wrap it in quotes:-
'CreateDate' => set_value('NOW()'),
Or in PHP you could do:-
'CreateDate' => set_value((new DateTime())->format('Y-m-d H:i:s')),
Nearly right,
I tried it without the set_value in so
'CreateDate' => set_value(date('Y-m-d H:i:s')),
And that worked. dont know what difference it makes

MySQL query for dates with CakePHP

I'm trying to select the values that fall between 2 dates, so I'll have to use <= and >=, however, my query is seemingly behaving as just less than or greater than and not considering values equal to the date.
I'm using CakePHP which saves dates in "Y-m-d h:i:a" format. I wanted to find dates on given week intervals (starting on Sundays), so I used the following.
$start_date = date('Y/m/d', strtotime('last Sunday', strtotime($timestamp)));
$formatted_start_date = str_replace("/","-",$start_date);
I tried to do find $start_date formatted as "Y-m-d" but then it wouldn't find the correct date, so I switched it to the way it is and used str_replace to format it to using "-" instead of "/".
$date_query = $this->Order->query("select * from orders where id = '$id' and created => '$formatted_start_date' and created <= '$current_timestamp' ");
Considering the time values in my database are in "Y-m-d h:i:a" format, can I use "Y-m-d" for date comparison? Is it possible to do a MySQL query that involves both LIKE and <= ?
No need to do a str_replace() - just get the Y-m-d:
$start_date = date('Y-m-d', strtotime('last Sunday', strtotime($timestamp)));
Then, instead of manually creating a query, use the CakePHP conventions (yes, you can use Y-m-d for date comparison even though the datetimes stored in the database are Y-m-d H:i:s)
$this->Order->find('all', array(
'conditions' => array(
'id' => $id,
'created >=' => $start_date,
'created <=' => $end_date . ' 23:59:59',
'my_field LIKE' => '%whatever%'
));
Though - this seems kind of strange - usually you're either looking for something by 'id' OR by a date range - not both. But - maybe you have a reason :)
And as you can see above, yes, you can add a 'LIKE' also if you need.
Above answer is totally correct, but you can take easier approach using cakePHP time helper, which has function daysAsSql, it transcribes and time-readable strings into database range.
http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::daysAsSql
Just add condition's array like this.
$resl = $this->DBNAME->find('all',array(conditions=>array('date1>date','date1<date')));
Replace 'date' with your date.
This is worked for me.
Try this in your controller
$searchTutorQuery = $this->Tutordetails->find('all', array(
'conditions' => array(
"User.zip" => $zipcode1,
"Tutordetails.user_id"=>$uid,
"Tutordetails.subject_id" => $subjectName,
"Tutordetails.hourly_rate >=" => $hourly_rate
),
//"User.id =" => $userid,
'fields' => array('user_id', 'Tutordetails.subject_id', 'Tutordetails.hourly_rate',
'User.zip', 'Tutordetails.zip'),
'order' => array('Tutordetails.id DESC')
));

Categories