Building an Array with a NOW() command for datetime - php

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

Related

SQL Query using INSERT INTO...SELECT and ON DUPLICATE UPDATE (codeigniter 3.x)

I'm currently creating a little tool for logs and i have an hard time working with mysql tables.
Here are my two tables:
CREATE TABLE site_logs
(
id int auto_increment,
level VARCHAR(45),
severity varchar(45),
uri varchar(255),
message VARCHAR(255),
trace varchar(255),
device varchar(45),
os varchar(45),
browser varchar(45),
ip varchar(45),
created_ at datetime
);
CREATE TABLE site_logs_stats
(
id int auto_increment,
log_id int,
date datetime,
count int,
);
Here is the situation: Every hour i parse my logs file and retrieve an $result array where i got each error and the number of occurences during the hour.
Next I insert the values in a table like this :
$result = array_values($result);
foreach ($result as $res) {
$this->db->insert('site_logs',array(
'level' => $res['level'],
'severity' => $res['severity'],
'uri' => $res['uri'],
'message' => $res['short_message'],
'trace' => $res['short_trace'],
'device' => $res['device'],
'os' => $res['os'],
'browser' => $res['browser'],
'ip' => $res['ip']
));
What I want to do:
In the site_logs table i only want unique errors (if there is the same error a 14:00 and 16:00 i want it to be writen one time in this table). If the error got the same level, severity, uri and trace then i considere this is the same error.
In the second table i the history of each unique error ex: if the same error appears at 14:00 and at 16:00 i want to have the site_logs.log_id 2 times, the hours they're writen and the number of occurence during the slot ( ex 14:00 -> 15:00 and 15:00-> 16:00).
I tried a lot of different queries but failed.
EDIT:
This is now how i insert datas in site_logs table:
$result = array_values($result);
foreach ($result as $res) {
$this->db->replace('site_logs',array(
'level' => $res['level'],
'severity' => $res['severity'],
'uri' => $res['uri'],
'message' => $res['short_message'],
'trace' => $res['short_trace'],
));
with unique key on ID, it seems to work pretty well, i've deleted other fields for an easier sorting and avoid duplicated except by ip/ browser etc...
So now i work on the second part where i must insert site_logs.id in site_log_stats and count occurence each hours. (i'm thinking about 'last_insert' or something like this.

insert current datetime to custom wordpress datetime column

I have an issue with inserting current datetime to custom wordpress datetime column. I've used curent_time function I also used date('Y-m-d H:m:s') as value for the column but it did not work.
I will provide my code for any suggestions:
global $wpdb;
$load_rec_table = $wpdb->prefix.'load_rec';
// Insert into load record table
$wpdb->insert($load_rec_table,array(
'rec_date' => current_time('mysql'),
'total_load' => $_POST['totalPower'],
'total_gap' => $_POST['totalGap'],
'carriage' => $_POST['carriage']
));
You can use NOW() or CURRENT_TIMESTAMP() functions of Mysql
global $wpdb;
$load_rec_table = $wpdb->prefix.'load_rec';
// Insert into load record table
$wpdb->insert($load_rec_table,array(
'rec_date' => NOW(),
'total_load' => $_POST['totalPower'],
'total_gap' => $_POST['totalGap'],
'carriage' => $_POST['carriage']
));

PHP MySQL Duplicate entry exception - InsertMulti with OnDuplicate

I am using ThingEngineer/PHP-MySQLi-Database-Class and I am trying to perform a multiple insert while using OnDuplicate. The goal is to insert a new product record if the 'sku' does not already exist. If the 'sku' does exist then the 'name' should be updated instead of creating a new entry.
MySQL Schema:
CREATE TABLE `products` (
`product_pk` bigint(9) NOT NULL,
`product_id` int(20) UNSIGNED NOT NULL,
`name` varchar(255) NOT NULL,
`sku` varchar(16) NOT NULL,
`category` int(10) DEFAULT NULL,
`last_update` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
ALTER TABLE `products`
ADD PRIMARY KEY (`product_pk`),
ADD UNIQUE KEY `sku` (`sku`);
ALTER TABLE `products`
MODIFY `product_pk` bigint(9) NOT NULL AUTO_INCREMENT;
PHP:
$sDate = date("Y-m-d H:i:s");
$lastid = $db->rawQuery('SELECT MAX( product_id ) AS max FROM products');
(!$lastid || !isset($lastid[0]['max'])) ? $pid = 0 : $pid = $lastid[0]['max']++;
foreach ($data as $item){
if (isset($item['sku']) && !null == $item['sku']){
$prod[$pid]['product_id'] = $pid;
$prod[$pid]['sku'] = $item['sku'];
$prod[$pid]['name'] = substr($item['product-name'],0,255);
$prod[$pid]['last_update'] = $sDate;
$pid++;
}
}
$utfEncodedArray =encodeArray($prod, 'UTF-8');
$db->onDuplicate('name', 'product_pk');
$db->insertMulti('products', $utfEncodedArray);
function encodeArray($array, $type)
{
foreach($array as $key => $value)
{
if (is_array($value)){ $array[$key] = encodeArray($value, $type);}else{ $array[$key] = mb_convert_encoding($value, $type);}
}
return $array;
}
The error I receive is:
Uncaught mysqli_sql_exception: Duplicate entry 'ABC123' for key 'sku'
Here is a sample of the array $utfEncodedArray used on the insertMulti call:
Array(
[1] => Array
(
[product_id] => 1
[sku] => ABC123
[name] => product1
[last_update] => 2018-09-08 18:55:20
)
[2] => Array
(
[product_id] => 2
[sku] => ABC124
[name] => product2
[last_update] => 2018-09-08 18:55:20
)
)
Steps I have tried so far:
Dropped the 'products' table and created it again. Multiple times.
Tried using 'sku' instead of 'product_pk' in the onDuplicate call.
Tried multiple collation types
Tried using unique key on both 'sku' and 'product_id'
When I attempted this method all entries were inserted correctly but when running it again it generated duplicates instead of updating the existing row. Not sure how this happened seeing as both 'sku' and 'product_id' are unique.
The $prod array currently contains the same values. So every time I run this I would expect to see the 'last_updated' column to be updated every time after the initial inserts.
This is my first experience using onDuplicate and despite hours of searching and reading docs I am still lost. I was trying to let the db class handle the multiple insert from the array but I am not against trying raw queries while iterating over my array of products instead.
Of course as soon as I posted this I find the issue...
Found a fork of the database class which resolved issues with insertMulti while using onDuplicate:
should fix insertMulti() if onDuplicate() is set

wpdb insert with no ID

I'm new in WordPress
I'm trying to insert on database without knowing the id, here what I'm trying to do:
$create = $wpdb->insert('wp_ito_plan', array('name' => $_POST['name'], 'tickets' => $_POST['tickets'], 'price' => $_POST['price'], 'visits' => $_POST['visits']));
and I got this error:
WordPress database error: [Duplicate entry '0' for key 'PRIMARY']
INSERT INTO `wp_ito_plan` (`name`,`tickets`,`price`,`visits`) VALUES ('asd','123','123','123')
I tried adding to the array: 'id' => $wpdb->insert_id, but stills the same.
How can I fix this? Do I need to check what is the last ID on database and then increment? There's no easiest way?
It appears as though you aren't auto incrementing the ID column so you're insert is going to overwrite an existing row. Set the ID column to auto increment and it should work fine.

PHP date() function inserting zeros into database

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.

Categories