How to set current date and time in table field using zend - php

I am having table called users with following fields ,
is_login(tinyint(1)) and last_login(datetime).
Below is the piece of code to update when user is online using Zend,
public function updateLastLoginDetails($id){
$currentDateTime = date('Y-m-d H:i:s');
$data = array('is_online' => 1,'last_login'=>$currentDateTime);
$this->_db->update( 'users', $data,'id = '.$id);
}
Here i am using $currentDateTime = date('Y-m-d H:i:s'); to store current data and time. But it seems not ok with time.
Kindly suggest me the best way to store current data and time using Zend .
Thanks in Advance,
Dinesh Kumar Manoharan

I'm not exactly sure what's causing your problem, but I find using NOW() to be easier. Also, you should ensure the variable $id gets quoted in the update's where condition.
public function updateLastLoginDetails($id){
$data = array('is_online' => 1, 'last_login' => new Zend_Db_Expr('NOW()'));
$this->_db->update('users', $data, array('id = ?' => $id));
}

It looks like you forgot to use $data anywhere in your code!
public function updateLastLoginDetails($id){
$currentDateTime = date('Y-m-d H:i:s');
$data = array('is_online' => 1, 'last_login'=>$currentDateTime);
$this->_db->update('users', $data, 'id = '. (int)$id);
}
You might want to consider using a TIMESTAMP field in place of a DATETIME for last_login and have MySQL update it automagically.

Hi am I understanding correctly that the year month and day are being inserted correctly but not the hour minutes and seconds? If that is the case can you please provide use with a describe of the users table. Just execute "DESCRIBE users" in phpMyAdmin.
If that is the case it could be that the field is of type DATE and not DATETIME.

Related

Insert the current date time using Laravel

I want to store the current date time in MySQL using the following Laravel function. Actually, I stored a static date. Instead of this, how can I store the current date time in the created_at and updated_at fields in the database?
function insert(Request $req)
{
$name = $req->input('name');
$address = $req->input('address');
$data = array("name" => $name, "address" => $address, "created_at" => '2017-04-27 10:29:59', "updated_at" => '2017-04-27 10:29:59');
DB::table('student')->insert($data);
echo "Record inserted successfully.<br/>";
return redirect('/');
}
Use the Laravel helper function
now()
Otherwise, use the carbon class:
Carbon\Carbon::now()
It is used like this:
$data = array("name" => $name,"address" => $address,"created_at"=> Carbon::now(),"updated_at"=> now());
DB::table('student')->insert($data);
For more information, see now()
You can also use this to get the current date time. It's working.
$current_date = date('Y-m-d H:i:s');
And also I have updated and set things in your function. You have to add this:
function insert(Request $req)
{
$name = $req->input('name');
$address = $req->input('address');
$current_date_time = date('Y-m-d H:i:s');
$data = array("name" => $name,
"address" => $address,
"created_at" => $current_date_time,
"updated_at" => $current_date_time);
DB::table('student')->insert($data);
echo "Record inserted successfully.<br/>";
return redirect('/');
}
Use this in your database query:
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
You can use the DateTime object.
Look at the below code:
$curTime = new \DateTime();
$created_at = $curTime->format("Y-m-d H:i:s");
$updateTime = new \DateTime();
$updated_at = $updateTime->format("Y-m-d H:i:s");
Use
use Carbon\Carbon;
at the header of the controller. This code work for Laravel 9:
$updated = Carbon::now();
You may save it inside a variable and use the variable for inserting and updating statements or for any other purpose.
During migration, I defined the column check_at as datetime. And I used the following command for table creation.
php artisan migrate
It generates a timestamp-type column in MySQL. I am passing the variable $updated for update purposes. While using phpMyAdmin, I can see the column check_at has data in date-time format.

update date to next day in laravel

I want to update my date to next day date. How Can I do it?
Now I do it using this.
$calendar = Calendar::find($id);
$calendar->update(['started_at' => $calendar->started_at->addDay(1)));
or I can do it
$calendar->started_at->addDay(1);
$calendar->save();
But this solutions is bad for me because there are 2 request in database. I wont do it using only one request.
Is there a way to dynamically update date to next day date?
For example
Calendar::where('id', $id)->updateToNextDay('started_at');
I find also sql equivalent
UPDATE `calendar` SET `started_at` = `started_at` - INTERVAL 1 DAY;
Thanks for attention.
Calendar::where('id', $id)->update() is just syntactical sugar. This proxies you to the Query Builder and is the same as running DB::table('calendar')->where('id', $id)->update();
The power of a model in an ORM is obtaining the data from the database, mapping it to properties in an object, and then manipulating that object. The overhead of a single select for an update is pretty small and if you're worried about that overhead in the development phase, you're probably overoptimizing.
If you wish to forego the select, you can use the Query Builder with a raw SQL expression. Either will call the Query Builder and run the same exact query:
Calendar::where('id', $id)
->update(['started_at' => DB::raw("started_at + INTERVAL 1 DAY")]);
or
DB::table('calendars')->where('id', $id)
->update(['started_at' => DB::raw("started_at + INTERVAL 1 DAY")]);
This should work
Calendar::where('id', $id)->update([
'started_at' => DB::raw("DATE_ADD(started_at, INTERVAL 1 DAY)")
]);
Let me know :)
$startDate = date_timestamp_get($calendar->started_at);
$date = date('Y-m-d H:i:s', strtotime('+1 day', $startDate));
$calendar->update(['started_at' => $date]);
You can write your own method in Calendar model like,
public function updateToNextDay(string $column)
{
$this->update([
$column => \Db::raw("$column + INTERVAL DAY 1");
]);
}
Not tested, but it should work.

Trouble with date and time formats saving in my database

I have trouble saving my date and time values. I tried different formats, here the actual try.
validator in my form:
$datum=$this->CreateElement('text','datum')
->setAttrib('size', '10')
->addValidator(New Zend_Validate_Date('MM-DD-YYYY'));
$zeit=$this->CreateElement('text','zeit')
->setAttrib('size', '10')
->addValidator(new Zend_Validate_Date(array('format' => 'H:i:s')));
Snippet of my Controller addAction
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$logenr = $this->_getParam('kopfnr', 0);
$kopfnr = $logenr;
$dat= $form->getValue('datum');
$zeit = $form->getValue('zeit');
$thema = $form->getValue('thema');
$aktermine = new Application_Model_DbTable_Aktermine();
$aktermine->addTermine( $kopfnr, $dat, $zeit, $thema);
And, my add function in my database class:
public function addTermine($kopfnr, $datum, $zeit, $thema)
{
$data = array(
'kopfnr' => $kopfnr,
'datum' => $datum,
'zeit' => $zeit,
'thema' => $thema,
);
$this->insert($data);
}
I´m using a mySQL database on a WAMP installation.
Where is my error? As a remark I want to say, I get a new record, the value of "thema" and the keys are properly saved, so I think it must be some format thing somewhere.
EDIT: I get a new record but the fields date and time are empty. I get no errors
NEW: I added a debug test in my controller to see what comes for the date value, here is the answer:
string '01-04-2016' (length=10)
(I put in 01-04-2016)
By reading your comments I understand you have two problems. The first one is putting the date into your table and the second is to let the user use the normal date format (dd/mm/yyyy).
First problem is solved when you reformat the user input before putting it into the database.You can add the following line into the $form->isValid($formData) part:
$dat = (new DateTime($form->getValue('datum')))->format('Y-m-d');
This oneliner will convert the date from 'dd-mm-yyyy' to 'yyyy-mm-dd'.
thanks, after the suggestion to debug I changed the format of my date like this: $test1=date('Y/m/d',strtotime($dat));
And now it works!

how to use sql NOW( ) function in laravel

I have used sql's now() function several times in normal query in php db connectivity...
But in laravel it does not displays anything and also the data is not inserted
the code I am using is:
$exercise = Exercise::insert(
array( 'fk_users_id' => '1',
'fk_equipments_id' => $equipment,
'muscular_group' => $muscular,
'exercise_name' => $postedContent['exercise_name'],
'exercise_type' => $postedContent['type'],
'Status' => '1',
'DateCreated' => 'NOW( )',
'DateModified' => 'NOW( )')
);
it stores the data into the database but the time in not stored in any of the columns
at first my method was:
$exerciseDetails = Input::all();
$exercise = Exercise::create($exerciseDetails);
the above method updates date and time itself and worked fine for other controllers but now I am having a problem of having a check box checked array in my post so it throws error
is there any other method in laravel to do this ??
Laravel comes with created_at and updated_at timestamp fields by default, which it keeps updated by itself.
http://laravel.com/docs/4.2/eloquent#timestamps
$now = DB::raw('NOW()');
$now variable can use in insert like
$user = new User;
$user->name = $name;
$user->created_at = $now;
use this
Carbon::now() instead 'NOW( )'
or use DB::raw('NOW()') instead 'NOW()'
You could be looking to direct query to get MySQL DB current Time.
You can go like this;
$currentDBtime = DB::select( 'select NOW() as the_time' );
$currentDBtime[0]->the_time;

How to structure database and populate Calendar in CodeIgniter 2 project?

I've searched SO and Google and can't quite find what I need.
I'm building a simple Event Calendar with CodeIgniter 2. As per the CodeIgniter documentation, this is the basic code structure and it's working...
// $data[2] contains the data for day #2, etc.
$data[2] = 'event title 1';
$data[8] = 'event title 2<br/>event title 3';
$data[13] = 'event title';
$data[24] = 'event title';
// {content} in template is where $data is inserted for each day
$prefs = array (
// my calendar options
'template' => '
{cal_cell_content}{day}<br/>{content}{/cal_cell_content}
{cal_cell_content_today}<div class="highlight">{day}<br/>{content}</div>{/cal_cell_content_today}'
);
$this->load->library('calendar', $prefs);
$year = ($year === FALSE ? date('Y') : $year);
$month = ($month === FALSE ? date('m') : $month);
echo $this->calendar->generate($year, $month, $data);
Now comes how I've set up my database table...
Each Event has a title field and that creates the $slug. (~/events/view/title-slug)
Each Event has a date field and the data format is mm/dd/yyyy
Now, I'm thinking about how I'd query the database for a particular month/year and extract the data to insert into each $data[] variable.
It seems like I'll need to do the following:
create new columns in my database table for month, day, and year.
take my date input data, after it's validated, and save it into date column.
split apart my date input data, and save each piece into month, day, and year columns.
Then I would simply query my database for year & month, then loop through these results to construct my $data[] array for each day.
Is this the correct way I should be approaching this problem? It seems very redundant to have a date column as well as month, day, and year columns. Can it be done with only the date (mm/dd/yyyy) column? Too simple? Too complex? I'd like to avoid giving the user more than one field for entering a date, and ultimately I'll have a jQuery date-picker to help ensure the proper data format.
I know this may seem like a simple problem, but I've failed to locate simple code examples online. Most of the ones I've found are out of date (CI instead of CI2), too complex for what I'm doing, or use daily content items which have URI segments that already contain the date (~/events/view/yyyy/mm/dd).
EDIT:
This is how my Model is presently setup:
return $this->db->get_where('events', array('yyyy' => $year, 'mm' => $month))->result_array();
You can leave everything as-is and just structure your query to return the month and year as separate columns:
in SQL:
SELECT id,
title,
description,
MONTH(date_field) as event_month,
YEAR(date_field) as event_year
FROM my_table
... etc ...
and in Active Record (taken from here):
$this->db->select('id');
$this->db->select('title');
$this->db->select('description');
$this->db->select("MONTH(date_field) AS event_month");
$this->db->select("YEAR(date_field) AS event_year");
$query = $this->db->get('my_table');
$results = $query->result();
Firstly, I changed my date column into the MySQL "date" format, yyyy-mm-dd, in order to take advantage of the built-in MySQL date functions.
My original $query is as follows, where the 'yyyy' and 'mm' are my redundant "year" and "month" columns:
$this->db->get_where('events', array('yyyy' => $year, 'mm' => $month))->result_array();
I simply changed it into the following using the built-in MySQL date functions:
$this->db->get_where('events', array('YEAR(date)' => $year, 'MONTH(date)' => $month))->result_array();
This solved the question. Now I no longer need to maintain the extra columns for "year" and "month".
Additionally, I can assign the "day" portion of the date column to a virtual column called dd by using the MySQL "alias" function:
$this->db->select('DAY(date) AS dd');
However, this would fail since it over-rides CI's default select('*'). So you'll have to select() all the relevant columns first or it will give an error:
$this->db->select('*');
$this->db->select('DAY(date) AS dd');
And putting it all together in the Model:
// select all relevant columns
$this->db->select('*');
/* use MySQL date functions to creates virtual column called 'dd' containing
"day" portion of the real 'date' column. */
$this->db->select('DAY(date) AS dd');
/* use MySQL date functions to match $year and $month to "year" and "month"
portions of real 'date' column. */
return $this->db->get_where('events', array('YEAR(date)' => $year, 'MONTH(date)' => $month))->result_array();

Categories