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;
Related
This is a big puzzle for us.
We have a table, where we have 2 columns, which both generally are the NOW DateTime value such as: 2022-07-11 09:00:00.000
However 1 column appears to randomly enter: 1970-01-01 01:00:00.000 instead of the NOW DateTime value. Whereas the other column always works.
We have 2 different systems entering data in to the table, and both have the same entering issue.
Using the MySQL insert such as:
$value = ":CaseRef,:DueDateTime,:CreatedBy, NOW(), :AssignedTo";
$params = array();
$params[':CaseRef'] = $Data['CaseRef'];
$params[':DueDateTime'] = $Data['DueDateTime'];
$params[':CreatedBy'] = $Data['CreatedBy'];
$params[':DateCreated'] = $Data['DateCreated'];
$params[':AssignedTo'] = $Data['AssignedTo'];
$stmt = DB::prepare("INSERT INTO Data_Table ($sql) VALUES ($value)");
$stmt->execute($params);```
In our API we have this:
I understand your comment. But in the API, we have this:
$currentDatetime = date('Y-m-d H:i:s');
Which populates an array:
$actionListData = [
'CaseRef' => $caseRef,
'DueDateTime' => $currentDatetime,
'CreatedBy' => 0,
'DateCreated' => $currentDatetime,
'AssignedTo' => $assignedTo,
];
Yet when the data enters the DB table, the DueDateTime most of the time is the set DateTime and on random occasions it enters as 1970-01-01 01:00:00.000? How / Why could this happen?
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.
In some part of my app I need to update only the field is_active of some table with a lot of fields. What is the best approach to update only this field and avoid the validations and requiriments of all other fields?
And if you want to update particular row only , use this:
$users= TableRegistry::get('Users');
$user = $users->get($id); // Return article with id = $id (primary_key of row which need to get updated)
$user->is_active = true;
// $user->email= abc#gmail.com; // other fields if necessary
if($users->save($user)){
// saved
} else {
// something went wrong
}
See here (Updating data in CakePHP3).
This will work:
$users = TableRegistry::get('Users');
$query = $users->query();
$query->update()
->set(['is_active' => true])
->where(['id' => $id])
->execute();
http://book.cakephp.org/3.0/en/orm/query-builder.html#updating-data
When you don't want callbacks to be triggered, just use updateAll()
$table->updateAll(['field' => $newValue], ['id' => $entityId]);
Using the example here: http://book.cakephp.org/3.0/en/orm/database-basics.html#running-update-statements. Run the code below to update all records in table_name_here table with a new value for is_active column.
use Cake\Datasource\ConnectionManager;
$connection = ConnectionManager::get('default');
$connection->update('table_name_here', ['is_active' => 'new_value_here']);
I faced this issue when upgrading my project from 2.10 to 3.x.
In 2.10 you could update a single field using:
$this->Menus->saveField('css', $menucss);
But since this method was deprecated, we do as below now, considering that callbacks will not be triggered:
$this->Menus->updateAll(['css' => $menucss], ['id' => $menu_id]);
The other answers don't use internationalization and other models props, callbacks, etc.
I think this is because of the query builder, it does not use the models and so their behaviors, therefore you should use:
$this->loadModel('Inputs');
$input = $this->Inputs->find()->where(['`key`' => $this->request->data['id']])->first();
$this->Inputs->patchEntity($input, ['prop' => $this->request->data['prop']]);
if ($this->Inputs->save($input)) {
die(json_encode(true));
} else {
die(json_encode(false));
}
I am using Cakephp 3.0.2. I would like to add a new record. A complete record $this->request->data would look something like this;
'date_taken' => [
'month' => '01',
'day' => '05',
'year' => '2015',
'hour' => '02',
'minute' => '51'
],
'moves_per_minute' => '80',
'person_id' => '1'
However, I want to HTTP Post $this->request->data such that it looks like this;
'moves_per_minute' => '80',
'person_id' => '1'
The dates_taken data should be updated automatically by using the current time.
I defined the column dates_taken as DATETIME type and default as CURRENT_TIME_STAMP. When I do a HTTP Post and send $this->request->data over leaving date_taken empty, the new row cannot be added.
This is how my controller code looks like;
$newRecord = $this->newRecords->newEntity();
if ($this->request->is('post')) {
$newRecord = $this->newRecords->patchEntity($newRecord, $this->request->data);
if ($this->newRecords->save($newRecord))
{
//success
Debugger::dump("Save success");
}
else
{
$this->response->statusCode(400); //bad request
Debugger::dump("Save failure");
}
}
How should a correct controller look like?
Add the columns 'created' and 'modified' to your database table (both DATETIME), then inside the model for the table add this line:
class ArticlesTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
// Timestamp is the correct, even though the field is a datetime
}
}
After you add new records, the datetime stored in the created field will be the exact time of creation and the modified field will be the last time you modify the record. Cake will do this by default every time you access this record through the entity.
More information can be found via the Timestamp documentation here: http://book.cakephp.org/3.0/en/orm/behaviors/timestamp.html
You could also save the current time by using the Time library and manually setting it in the entity before saving:
$time = Time::now();
$newRecord->date_taken = $time;
$this->newRecords->save($newRecord);
Again assuming the date_taken field is a datetime object in your table. I'd recommend letting the database set it for you rather than this method, though.
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.