Since MySQL evidently cannot automatically insert the function now() in a datetime field in adding new records like some other databases, based on comments, I'm explicitly trying to insert it using an SQL statement. (People seem to think timestamp with curdate() is not the answer due to the various limitations of timestamp.) There are numerous articles on the web suggesting inserting now() using SQL should work.
When I try to insert the date time using the SQL statement, however, the field does not populate with the current time/date, but it only gives me the default 0000-00-, etc. This is probably a syntax error, but it's driving me crazy, so I am posting it.
mysql_query("INSERT INTO users (first, last, whenadded) VALUES ('$first', '$last', now())";
It inserts first and last, but nothing for when added, leaving 0000-00-00, etc. in the whenadded field.
The field type is datetime, it has no collation, attributes, null default or extra. BTW, I tried putting now() in single quotes... It threw an error.
NOW() normally works in SQL statements and returns the date and time. Check if your database field has the correct type (datetime). Otherwise, you can always use the PHP date() function and insert:
date('Y-m-d H:i:s')
But I wouldn't recommend this.
You forgot to close the mysql_query command:
mysql_query("INSERT INTO users (first, last, whenadded) VALUES ('$first', '$last', now())");
Note that last parentheses.
Like Pekka said, it should work this way. I can't reproduce the problem with this self-contained example:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->exec('
CREATE TEMPORARY TABLE soFoo (
id int auto_increment,
first int,
last int,
whenadded DATETIME,
primary key(id)
)
');
$pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,1,Now())');
$pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,2,Now())');
$pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,3,Now())');
foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $row ) {
echo join(' | ', $row), "\n";
}
Which (currently) prints
1 | 0 | 1 | 2012-03-23 16:00:18
2 | 0 | 2 | 2012-03-23 16:00:18
3 | 0 | 3 | 2012-03-23 16:00:18
And here's (almost) the same script using a TIMESTAMP field and DEFAULT CURRENT_TIMESTAMP:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->exec('
CREATE TEMPORARY TABLE soFoo (
id int auto_increment,
first int,
last int,
whenadded TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
primary key(id)
)
');
$pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,1)');
$pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,2)');
sleep(1);
$pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,3)');
foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $row ) {
echo join(' | ', $row), "\n";
}
Conveniently, the timestamp is converted to the same datetime string representation as in the first example - at least with my PHP/PDO/mysqlnd version.
The only reason I can think of is you are adding it as string 'now()', not function call now().
Or whatever else typo.
SELECT NOW();
to see if it returns correct value?
Currently, and with the new versions of Mysql can insert the current date automatically without adding a code in your PHP file. You can achieve that from Mysql while setting up your database as follows:
Now, any new post will automatically get a unique date and time.
Hope this can help.
What about SYSDATE() ?
<?php
$db = mysql_connect('localhost','user','pass');
mysql_select_db('test_db');
$stmt = "INSERT INTO `test` (`first`,`last`,`whenadded`) VALUES ".
"('{$first}','{$last}','SYSDATE())";
$rslt = mysql_query($stmt);
?>
Look at Difference between NOW(), SYSDATE() & CURRENT_DATE() in MySQL for more info about NOW() and SYSDATE().
now()
worked for me .
but my field type is date only and yours is datetime. i am not sure if this is the case
These both work fine for me...
<?php
$db = mysql_connect('localhost','user','pass');
mysql_select_db('test_db');
$stmt = "INSERT INTO `test` (`first`,`last`,`whenadded`) VALUES ".
"('{$first}','{$last}','NOW())";
$rslt = mysql_query($stmt);
$stmt = "INSERT INTO `users` (`first`,`last`,`whenadded`) VALUES ".
"('{$first}', '{$last}', CURRENT_TIMESTAMP)";
$rslt = mysql_query($stmt);
?>
Side note: mysql_query() is not the best way to connect to MySQL in current versions of PHP.
Just go to the column whenadded and change the default value to CURRENT_TIMESTAMP
Related
I am having trouble inserting null values into date fields into a MySQL table.
Here is the insert query:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ("'.$string1.'", "'.$string2.'", '.$date1.', '.$date2.')';
Columns s1 and s2 take string values and d1 and d2 take dates. When I run this query with only the string fields, there is no problem.
The date values can be either set or null, so I have not included the quotation marks in the query, but have instead added them to the variable earlier on. This is the php code I am using to set the date values:
if (empty($date1)){
$date1 = NULL;
}
else{
$date1part = explode("/",$date1);
$date1 = '"'.$date1part[2].'/'.$date1part[1].'/'.$date1part[0].'"';
}
When the date values are all set, the record is inserted correctly. However, when either of the dates is null, nothing is inserted.
Why can't I just insert null values into MySQL like this?
Try this:
$query = "INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ('$string1', '$string2', " . ($date1==NULL ? "NULL" : "'$date1'") . ", " . ($date2==NULL ? "NULL" : "'$date2'") . ");";
so for example if you put this into query:
$string1 = "s1";
$string2 = "s2";
$date1 = NULL;
$date2 = NULL;
result should be:
INSERT INTO table (column_s1, column_s2, column_d1, column_d2) VALUES ('s1', 's2', NULL, NULL);
You should convert the null variable into a NULL string first
Like this:
if(is_null($date1)){
$date1 = 'NULL';
}
If you are using a MySQL date column, you must also specify that it should hold null when creating it, like this:
CREATE TABLE `table` (
id INT NOT NULL AUTO_INCREMENT,
date DATE NULL DEFAULT NULL,
PRIMARY KEY(id)
)
It is also very important that you perform the query with bound parameters, for example using pdo
http://www.php.net/manual/en/pdo.construct.php
http://php.net/manual/en/pdo.prepared-statements.php
How do I insert NULL values using PDO?
Something like this:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES (?, ?, ?, ?)';
$stmt = $db->prepare($query);
$stmt->execute(array($string1,$string2,$date1,$date2));
If NULL does not work, just pass your date as "0000-00-00":
$chequeDate = "0000-00-00";
Backslash N is another way to express NULL in MySQL.
Try putting the value (backslash N): \N into one of the parameters like this:
$data1 = "\N";
$sql="insert into tablename set column_s1='" . $data1 .
"', column_s2='" . data2 .
"', column_s3='" . $data3 . "'";
Reference: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
In Derby, If you want to insert values except the ones you have declared Null (column_d1, column_d2), sql:
INSERT INTO DB.table (column_s1, column_s2) VALUES ('s1', 's2');
Probably answer is unneeded at this moment, but I found solution exactly I have been searching. Use an Expression to pass NULL like this:
['some_date_to_update' => new Expression('NULL')]
Hence, MySQL will understand what you want, and save (NULL) in DB instead of storing 0-dates. Hope this will help somebody.
In Mysql DATE data type Default NULL means
Some version set as 0000-00-00
Some version set as 1970-01-01
Years later, if someone is still experiencing this issue, you want to use PDO and bind the variables, everything will be taken care of no need to handle the null variables yourself.
I'm writing a PHP/MySQL program. I need to add the current date each time a new record to the TABLE is added. I have a field called DATE_ADDED. I'm confused how to use CURDATE() function from MySQL to write this to the TABLE. Or should I from PHP use a date function to get today's date and pass it as a variable to be written to the TABLE? I don't need a TIMESTAMP, just YYYY-MM-DD.
Thanks!
You have to try with php like
$today = date("Y-m-d");
and then while adding data to your db give this value with the remaining
INSERT INTO table_name ( field1, field2,...DATE_ADDED )
VALUES
( value1, value2,...CURDATE());
You can set it as the default value for that column date_added in the table definition like so:
date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP
$regdate=date('Y-m-d');
$sql = "INSERT INTO table_name (fld_name1, fld_name2,fld_regdate) VALUES ('value1', 'value2', '$regdate')";
$rs = mysql_query($sql) or die('ERROR:' mysql_error());
$sql = 'INSERT INTO joke SET
joketext = :joketext,
jokedate = CURDATE()';
$s = $pdo->prepare($sql);
$s->bindValue(':joketext', $_POST['joketext']);
$s->execute();
Well I have a task to store "quotes" into a database (Already done this) and display them & sort them out for the most recent quotes. I'm assuming to get the "most recent", I'd need to store date/time of the submitted quote.
I am new to PHP and trying to learn, so I don't know how to exactly do this.
Here is the PHP for adding the quotes to the database. There are two columns in the table called "quotes" and "id". I'm guessing I will also need to make a column for the date too?
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
How would I also insert the date?
use CURDATE() if you want to insert the current date
example:
$query_auto = "INSERT INTO tablename (col_name, col_date) VALUE ('DATE: Auto CURDATE()', CURDATE() )";
but if you wqant it manually then should use this:
$query_manual = "INSERT INTO tablename (col_name, col_date) VALUES ('DATE: Manual Date', '2008-07-04')";
UPDATE
CREATE TABLE auto_ins
(
`MySQL_Function` VARCHAR(30),
`DateTime` DATETIME,
`Date` DATE,
`Time` TIME,
`Year` YEAR,
`TimeStamp` TIMESTAMP
);
INSERT INTO auto_ins
(`MySQL_Function`, `DateTime`, `Date`, `Time`, `Year`, `TimeStamp`)
VALUES
(“CURDATE()”, CURDATE(), CURDATE(), CURDATE(), CURDATE(), CURDATE());
If you only want the most recent quotes, you can simply sort your result set by their id DESC assuming the id is an auto-incremented value.
Yes, you need a third column lets say most_recent (defined as date or datetime) :
mysql_query("INSERT INTO entries (quote, most_recent) VALUES('$quotes', now())")
You will need at least couple of tables who submitted the quote and the quote table itself.
create table users(id int primary key not null, username varchar(32),pwd varchar(32));
you can add any info to that table like email address and so on.
create table quotes (
id int not null ,
user_id integer,
quote_text varchar(256),
inserted_date timestamp default current_timestamp ,primary key (id));
alter table quotes add constraint fk_users foreign key(user_id) references users(id);
Otherwise feel free to modify them.
It's not about php here its about DB design in general.
Use this code:
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = now().' - '.mysql_real_escape_string($quote);
// THIS WILL ADD THE DATE AND TIME TO YOUR $quotes STRING.
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
Say I have a table name auto_parts with these fields.
id, part, price, timestamp
and I insert a new row via php as so:
$query = "insert into auto_parts(id, part, price, timestamp)
values(1, 'axle', 200)"
mysql_query($query);
will that automatically add the timestamp.
Or do I have to insert a value for timestamp myself?
What you need to do is declare timestamp to be of type in your sql
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
and modify the query to
$query = "insert into auto_parts(id, part, price)
values(1, 'axle', 200)"
mysql_query($query);
$query = "insert into auto_parts(id, part, price, timestamp)
values(1, 'axle', 200, 'NOW()')"
mysql_query($query);
Do it in SQL itself instead of passing it ... its more efficient ... This is the corresponding post:
Auto TimeStamp new entry to DB (phpMyAdmin)
I know there are already answers to this question so I am kind of combining all answers and explaining a little bit.
There may be two ways to do this,
Change your table and make timestamp column to default CURRENT_TIMESTAMP
ALTER TABLE tablename MODIFY timestamp TIMESTAMP NOT NULL DEFAULT
CURRENT_TIMESTAMP
and modify your query like this, timestamp will be inserted automatically
$query = "insert into auto_parts(id, part, price) values(1, 'axle',
200)"; mysql_query($query);
If you have more than one timestamp table then you can make one as current timestamp and for other one use like this
ALTER TABLE tablename MODIFY timestamp TIMESTAMP NOT NULL
and modify your query like this
$query = "insert into auto_parts(id, part, price, timestamp) values (1, 'axle', 200, now())"; mysql_query($query);
Quoting MySQL INSERT manual - same goes for UPDATE:
Use the keyword DEFAULT to set a column explicitly to its default value. This makes it easier to write INSERT statements that assign values to all but a few columns, because it enables you to avoid writing an incomplete VALUES list that does not include a value for each column in the table. Otherwise, you would have to write out the list of column names corresponding to each value in the VALUES list.
So in short if I write
INSERT INTO table1 (column1,column2) values ('value1',DEFAULT);
A new row with column2 set as its default value - whatever it may be - is inserted.
However if I prepare and execute a statement in PHP:
$statement = $pdoObject->
prepare("INSERT INTO table1 (column1,column2) values (?,?)");
$statement->execute(array('value1','DEFAULT'));
The new row will contain 'DEFAULT' as its text value - if the column is able to store text values.
Now I have written an abstraction layer to PDO (I needed it) and to get around this issue am considering to introduce a
const DEFAULT_VALUE = "randomstring";
So I could execute statements like this:
$statement->execute(array('value1',mysql::DEFAULT_VALUE));
And then in method that does the binding I'd go through values that are sent to be bound and if some are equal to self::DEFAULT_VALUE, act accordingly.
I'm pretty sure there's a better way to do this. Has someone else encountered similar situations?
The only "workaround" I know for this is to use Coalesce() and Default(fieldname)
E.g.
$pdo = new PDO("mysql:host=localhost;dbname=test", 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("
CREATE TEMPORARY TABLE foo (
id int auto_increment,
x int NOT NULL DEFAULT 99,
y DATETIME NOT NULL DEFAULT '2010-03-17 01:00:00',
z varchar(64) NOT NULL DEFAULT 'abc',
primary key(id)
)
");
$stmt = $pdo->prepare('
INSERT INTO
foo
(x,y,z)
VALUES
(
Coalesce(:x, Default(x)),
Coalesce(:y, Default(y)),
Coalesce(:z, Default(z))
)
');
$stmt->bindParam(':x', $x);
$stmt->bindParam(':y', $y);
$stmt->bindParam(':z', $z);
$testdata = array(
array(null, null, null),
array(1, null, 'lalala'),
array(null, '2009-12-24 18:00:00', null)
);
foreach($testdata as $row) {
list($x,$y,$z) = $row;
$stmt->execute();
}
unset($stmt);
foreach( $pdo->query('SELECT id,x,y,z FROM foo', PDO::FETCH_NUM) as $row) {
echo join(', ', $row), "\n";
}
prints
1, 99, 2010-03-17 01:00:00, abc
2, 1, 2010-03-17 01:00:00, lalala
3, 99, 2009-12-24 18:00:00, abc
I tried replying to VolkerK answer, but couldnt find how. :( I'm kinda new to all this.
Anyway, I created a mysql function to use in conjuction with his COALESCE idea
CREATE FUNCTION NULLDEFAULT(colname VARCHAR(64), tablename VARCHAR(64), dbname VARCHAR(64)) RETURNS longtext DETERMINISTIC READS SQL DATA
BEGIN
DECLARE retval longtext;
SELECT
COLUMN_DEFAULT INTO retval
FROM
information_schema.COLUMNS
WHERE
TABLE_NAME = tablename
AND
COLUMN_NAME = colname
AND
TABLE_SCHEMA = dbname;
RETURN retval;
END
You would use it like this:
$stmt = $pdo->prepare("
INSERT INTO
foo
(x,y,z)
VALUES
(
Coalesce(:x, NULLDEFAULT('x', 'foo', 'database')),
Coalesce(:y, NULLDEFAULT('y', 'foo', 'database')),
Coalesce(:z, NULLDEFAULT('z', 'foo', 'database'))
)
");
That will return null if the column has no default value, and won't trigger the "Column has no default value" Error.
Of course you could modify it to not require the database parameter
Try changing this:
$statement = $pdoObject->
prepare("INSERT INTO table1 (column1,column2) values (?,?)");
$statement->execute(array('value1','DEFAULT'));
To this:
$statement = $pdoObject->
prepare("INSERT INTO table1 (column1,column2) values (?,DEFAULT)");
$statement->execute(array('value1'));
It seems to me that your original code will give you this:
INSERT INTO table1 (column1,column2) values ('value1','DEFAULT')
My code should give you this:
INSERT INTO table1 (column1,column2) values ('value1',DEFAULT)
i think that it is writing the String 'DEFAULT ' because it is escaped by pdo so there are parametres for bindvalue where you can specify the type of the value given so you can send a null with no quotes and it will be PDO::PARAM_NULL; and then default values will be put , but i'm not sure if there are similar parameters when binding with execute
if(is_int($param)){$pdoParam = PDO::PARAM_INT;}
elseif(is_bool($param)){$pdoParam = PDO::PARAM_BOOL;}
elseif(is_null($param)){ $pdoParam = PDO::PARAM_NULL;}
elseif(is_string($param)){$pdoParam = PDO::PARAM_STR;}
else{$pdoParam = FALSE;}
$this->_query->bindValue($k,$param,$pdoParam);