I have a feeddate column with the info below..
type : timestamp
attributes : on update CURRENT_TIMESTAMP
default : CURRENT_TIMESTAMP
and when I used PHP to INSERT INTO the rows with this code ..
$badgefeed = "INSERT INTO d VALUES ('','".$userID."','Badge','','".$badgeNAME."','".$badgeTYPE."','".$badgelv."','','')";
$badgefeedQ = mysql_query($badgefeed);
(feeddate is on the last column that NULL)
This feeddate doesn't update and be like 0000-00-00 00:00:00
but it's gonna work when I used PHP to UPDATE something that already had in the table.
Did I do anything wrong with my feeddate structure or the INSERT code is incorrect ?
Your query should be:
$badgefeed = "INSERT INTO d VALUES ('','".$userID."','Badge','','".$badgeNAME."','".$badgeTYPE."','".$badgelv."','')";
Don't use any value for the last column as you are using the timestamp as default value in MySQL. Just omit the last (blank) value from your query. In such a way, value for the concerned column will be considered null and thus default timesamp will will be used.
Insead of '' use null.
This way, mysql manages the value itself.
If you specify any value, the server will take your value, regardless other triggers, settings.
If you don't include the column in the insert statement or leave it blank (null), it will get set by the server, according to the defaults. In this case the default being on update CURRENT_TIMESTAMP
Related
I want to update the status column in my table, but the date column of the message is also updated. How can I only update the status column only without the date field ?
Data type:
Status => Varchar
messgae_date => Timestamp
Query :
"UPDATE mytable SET status='1' WHERE status='0'"
Thank's before ..
Please edit your question and post the entire DDL statement for creating the table. I believe it will become apparent.
Your post said that message_date is a timestamp. That's a special datatype in MySql and MariaDb that can autoupdate itself at insert or whenever any other data in a row is changed.
An auto-updated column is automatically updated to the current
timestamp when the value of any other column in the row is changed
from its current value. An auto-updated column remains unchanged if
all other columns are set to their current values. To prevent an
auto-updated column from updating when other columns change,
explicitly set it to its current value. To update an auto-updated
column even when other columns do not change, explicitly set it to the
value it should have (for example, set it to CURRENT_TIMESTAMP).
Again, please post the table DDL statement. The message_date column will probably look something like this.
`message_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
as i see every where even in here :
From the MySQL manual:
If an ENUM column is declared to permit NULL, the NULL value is a
legal value for the column, and the default value is NULL. If an ENUM
column is declared NOT NULL, its default value is the first element of
the list of permitted values.
But in my database is not like this !!!! Why ?
this is one of field structure :
`dead` enum('0','1') NOT NULL DEFAULT '0';
but why all data in the dead field is null ???
and if i chose that type to enter a value this will be list :
()Empty
(0)
(1)
Why always null is there ?
and another thing is when i use query like this :
UPDATE TABLE SET dead = 0 -> result : dead = null
UPDATE TABLE SET dead = 1 -> result : dead = 0
UPDATE TABLE SET dead = 2 -> result : dead = 1
Best Regards.
It is not clear what you are asking for.
Here is fiddle: http://sqlfiddle.com/#!9/8b24d0/1
As we can see when dead is not set in INSERT query:
insert into table1 (id) values (4);
mysql put there your default value '0' and that is what you were expecting I guess.
I don't know what version of mysql do you use, but in my fiddle it is clear that mysql doesn't allow to:
UPDATE table1 SET dead = 0;
Since it is enum, it only allows:
UPDATE table1 SET dead = '0';
And that is correct and expected behavior since you choose ENUM type for the column. So I can't reproduce described in OP behavior. If anybody else can?
GUESS I guess that you are trying to convert existing table column with existing data in that column and stuck. So to run alter table you should fix data first like:
UPDATE table1 SET dead='0' WHERE dead IS NULL;
So once you get data fixed you can try ALTER TABLE to set DEFAULT.
I am trying to update date whenever any updates occur on the record, the field type is datetime and I set the default value to CURRENT_TIMESTAMP. when update sql is excuted the result is all zeros!
0000-00-00 00:00:00
$sql = 'INSERT INTO product_shop_offers (id,product_id,shop_id,price,currency_id,added_by,last_update)'
. ' VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE id=?,shop_id=?,price=?,currency_id=?,added_by=?,last_update=?';
$this->db->query($sql, array(
$storeInfoArray['recordId'],
$productId,
$storeInfoArray['storeNameNo'],
$storeInfoArray['price'],
$storeInfoArray['currency'],
$addedBy,
'CURRENT_TIMESTAMP()',
$storeInfoArray['recordId'],
$storeInfoArray['storeNameNo'],
$storeInfoArray['price'],
$storeInfoArray['currency'],
$addedBy,
'CURRENT_TIMESTAMP()'
))
Note: I checked Similar problem question but I didn't understand the problem!!can somebody help please.
Is it because you are binding in the string 'CURRENT_TIMESTAMP()'.. I'm not sure you can do that and it is being converted to zeros.
If you have the default set in the database, why bother binding it in at all? Just remove the field from the statement.. oh and you'll need to add the attribute ON UPDATE CURRENT_TIMESTAMP to the column:
ALTER TABLE product_shop_offers
MODIFY COLUMN last_update DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
If you need it otherwise, you may have to write it into the query directly.
I think it should be helpful for you
MySQL CURRENT_TIMESTAMP field updates on every update
Change CURRENT_TIMESTAMP() to NOW()
Another possible way is to set the field type from datetime to timestamp
i am using a timestamp type column in my mysql database, and i have enabled the option for auto update timestamp, but the time stamp works only on update command and not on insert
i am using navicat mysql client
Thanks in advance.
Try assigning the current timestamp as the default value along with enabling auto-update. That should work for you.
See: current_timestamp
Did you mean something like this..
To set the TIMESTAMP column in either table to the current timestamp at insert time, explicitly assign it that value.
INSERT INTO t1 VALUES (NOW());
INSERT INTO t2 VALUES (CURRENT_TIMESTAMP);
http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
Set the column default value to CURRENT_TIMESTAMP.
If you are using a server side language to insert data into the table, you could simply insert the current date into that column. In PHP, for example, that would be
<?php
$time = time();
?>
I have a "bill_date" field that I want to be blank (NULL) until it's been billed, at which point the date will be entered.
I see that MySQL does not like NULL values in datetime fields. Do any of you have a simple way to handle this, or am I forced to use the min date as a "NULL equivalent" and then check for that date?
Thanks.
EDITED TO ADD:
Ok I do see that MySQL will accept the NULL value, but it won't accept it as a database update if I'm updating the record using PHP.
The variable name is $bill_date but it won't leave the variable as NULL if I update a record without sending a value to $bill_date -- I get this error:
Database query failed: Incorrect datetime value: '' for column 'bill_date' at row 1
I assume I need to actually send the word NULL, or leave it out of the update query altogether, to avoid this error? Am I right? Thanks!!!
MySQL does allow NULL values for datetime fields. I just tested it:
mysql> create table datetimetest (testcolumn datetime null default null);
Query OK, 0 rows affected (0.10 sec)
mysql> insert into datetimetest (testcolumn) values (null);
Query OK, 1 row affected (0.00 sec)
mysql> select * from datetimetest;
+------------+
| testcolumn |
+------------+
| NULL |
+------------+
1 row in set (0.00 sec)
I'm using this version:
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.0.45 |
+-----------+
1 row in set (0.03 sec)
Speaking of inserting NULL values through PHP code, given you are using prepared statements (as you definitely should), there is no problem with inserting NULL values. Just bind your variable the usual way, and all PHP variables that contain null values will be stored as NULL in MySQL.
Just make sure that your PHP variable indeed contains NULL and not an empty string.
This is a a sensible point.
A null date is not a zero date. They may look the same, but they ain't. In mysql, a null date value is null. A zero date value is an empty string ('') and '0000-00-00 00:00:00'
On a null date "... where mydate = ''" will fail.
On an empty/zero date "... where mydate is null" will fail.
But now let's get funky. In mysql dates, empty/zero date are strictly the same.
by example
select if(myDate is null, 'null', myDate) as mydate from myTable where myDate = '';
select if(myDate is null, 'null', myDate) as mydate from myTable where myDate = '0000-00-00 00:00:00'
will BOTH output: '0000-00-00 00:00:00'. if you update myDate with '' or '0000-00-00 00:00:00', both selects will still work the same.
In php, the mysql null dates type will be respected with the standard mysql connector, and be real nulls ($var === null, is_null($var)). Empty dates will always be represented as '0000-00-00 00:00:00'.
I strongly advise to use only null dates, OR only empty dates if you can. (some systems will use "virual" zero dates which are valid Gregorian dates, like 1970-01-01 (linux) or 0001-01-01 (oracle).
empty dates are easier in php/mysql. You don't have the "where field is null" to handle. However, you have to "manually" transform the '0000-00-00 00:00:00' date in '' to display empty fields. (to store or search you don't have special case to handle for zero dates, which is nice).
Null dates need better care. you have to be careful when you insert or update to NOT add quotes around null, else a zero date will be inserted instead of null, which causes your standard data havoc. In search forms, you will need to handle cases like "and mydate is not null", and so on.
Null dates are usually more work. but they much MUCH MUCH faster than zero dates for queries.
I had this problem on windows.
This is the solution:
To pass '' for NULL you should disable STRICT_MODE (which is enabled by default on Windows installations)
BTW It's funny to pass '' for NULL. I don't know why they let this kind of behavior.
It depends on how you declare your table. NULL would not be allowed in:
create table MyTable (col1 datetime NOT NULL);
But it would be allowed in:
create table MyTable (col1 datetime NULL);
The second is the default, so someone must've actively decided that the column should not be nullable.
If your datetime column is not accepting null values it might be not nullable, so you can update the column using this command:
ALTER TABLE your_table modify your_coloumn datetime null
And when you want to save a null field, you can leave it alone (not assigning anything to that field), or you can set it to Null (instead of '')
For what it is worth: I was experiencing a similar issue trying to update a MySQL table via Perl. The update would fail when an empty string value (translated from a null value from a read from another platform) was passed to the date column ('dtcol' in the code sample below). I was finally successful getting the data updated by using an IF statement embedded in my update statement:
...
my $stmnt='update tbl set colA=?,dtcol=if(?="",null,?) where colC=?';
my $status=$dbh->do($stmt,undef,$iref[1],$iref[2],$iref[2],$ref[0]);
...
I just discovered that MySQL will take null provided the default for the field is null and I write specific if statements and leave off the quotes. This works for update as well.
if(empty($odate) AND empty($ddate))
{
$query2="UPDATE items SET odate=null, ddate=null, istatus='$istatus' WHERE id='$id' ";
};
I just tested in MySQL v5.0.6 and the datetime column accepted null without issue.
Specifically relating to the error you're getting, you can't do something like this in PHP for a nullable field in MySQL:
$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . null . ')';
Because null in PHP will equate to an empty string which is not the same as a NULL value in MysQL. Instead you want to do this:
$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . (is_null($col2) ? 'NULL' : $col2). ')';
Of course you don't have to use is_null but I figure that it demonstrates the point a little better. Probably safer to use empty() or something like that. And if $col2 happens to be a string which you would enclose in double quotes in the query, don't forget not to include those around the 'NULL' string, otherwise it wont work.
Hope that helps!