In my query:
$cselect = mysql_real_escape_string($_POST['cselect']);
---------------
---------------
$sql = sprintf("INSERT INTO content
(id, catID, title, abstract, body, status, published, date, description_meta, keywords_meta)
VALUES ('', '%s', '%s','%s','%s','%s','%s','%s','', '' )", $cselect,$chead, $cabst,$ctext, $cp, $cradio, 'TIMESTAMP: Auto NOW()');
the output for date is:
0000-00-00 00:00:00
What is wrong in my query?
TIMESTAMP: Auto NOW() is definitely not a correct value for a timestamp string and MySQL silently (unless you check warnings or enable strict mode) converts it to zero timestamp.
You should either use a function NOW() (without quotes around it) or rather CURRENT_TIMESTAMP instead.
Instead of specifying the Date in your query change your date column to a Timestamp type, and then set its default value to CURRENT_TIMESTAMP.
This way you wouldn't even need to bother with the date column in your queries, once MySQL will handle that for you, by inserting the actual date in UTC when it receives your insert query.
Here goes the SQL query to change you date column:
ALTER TABLE `content ` CHANGE `date` `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
I hope this helps.
Any reason you're using sprintf() for this? You're not formatting any of the values, other than perhaps forcing things to be treated as strings. The following non-function version would be far more readable, using a heredoc
$sql = <<<EOL
INSERT INTO content
(id, catID, title, abstract, body, status, published, date, description_meta, keywords_meta)
VALUES
('', '$cselect', '$chead','$cabst','$ctext','$cp','$cradio', NOW(),'', '' );
EOL;
Note the NOW() call to fill in the date field. That returns the current date/time at the moment the query executes.
Please note that 'date' is a reserved word in MySQL and will cause syntax errors. You'll have to change the field name to something safe, and/or surround it with backticks (`) to 'escape' it.
As well, note that this way of building the query doesn't get around the fact that if any of this information is coming from untrusted sources you're wide open to SQL injection.
You can use date('Y-m-d h:i:s') instead of 'TIMESTAMP: Auto NOW()' for getting the current time.
Related
For example I use this to insert in table:
INSERT INTO `mytable` (`name`, `type`, `date`) VALUES ('Smit', 12, now());
Then I need get all or some rows from this table:
$st = $db->prepare("SELECT * FROM `mytable` WHERE id=:id");
$st->bindParam(':id', $id, PDO::PARAM_INT);
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
Where I receive $result[0]['date'] as string = "2016-09-10 21:00:00". Maybe PDO has some PDO::PARAM_ which can set all date fields to timestamp?
P.S. Yes I know about php strtotime() which I can use here, but in this case we do double conversion. I mean, if I understood this right, MySQL save datetime as unix timestamp and when we get it as string, then convert again to a timestamp, and it is not a good solution.
MySQL does not store DATETIME as a UNIX timestamp.
MySQL's TIMESTAMP data type may be stored internally like a UNIX-style timestamp, but in spite of this, the default output is formatted like YYYY-MM-DD HH:MM:SS. You will have to convert it back.
You can format the MySQL datetime as a UNIX timestamp using an SQL function:
$st = $db->prepare("SELECT UNIX_TIMESTAMP(date) FROM `mytable` WHERE id=:id");
$st->bindParam(':id', $id, PDO::PARAM_INT);
$st->execute([$id]);
$result = $st->fetchAll(PDO::FETCH_ASSOC);
See http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_unix-timestamp
It would be worth your time to review the other functions on that page. There are a lot of things you can do in SQL expressions.
Maybe PDO have some PDO::PARAM_ which can set all date fields to timestamp?
Nope, it doesn't.
There is no setting, neither in PHP, PDO or Mysql, that will tell mysql to return all dates as timestamps.
if i right understood, MySQL save datetime as unix timestamp
Nope, you understood it wrong.
and when we get it as string, then convert again in timestamp, it is not a good solution.
Don't worry about that. Just select your data in the format you need. As simple as that.
Do not optimize stuff that works all right. Do not solve problems that don't exist.
P.S. Yes I know about php strtotime() which i can use here, but in
this case we do double conversion. I mean, if i right understood,
MySQL save datetime as unix timestamp and when we get it as string,
then convert again in timestamp, it is not a good solution.
So if you want to avoid any conversions (manual or that under the hood) you shoud set up your field type in database as TIMESTAMP
https://dev.mysql.com/doc/refman/5.5/en/datetime.html
I have what is most likely a very simple question.. I am designing a simple blogging system and I am trying to put the current date into the table where the blog post is stored whilst waiting for administrator approval. but the method I have used puts 0000-00-00 into the date column! What I am using is as follows:
$query = "INSERT INTO blogentry VALUES ('".$mnam."','".date('d-m-Y h:m:s') ."\n"."','".$mcom."','".$approve."')";
I am relatively new to php so stumble accross errors like this all the time... but I cant seem to google this one!
Thanks guys!
So the easiest way to do this is just let MySQL handle it with the NOW() function:
INSERT INTO blogentry VALUES( ..., NOW(), ... )
Another option is to use TIMESTAMPs by changing your table - set the column to type TIMESTAMP with DEFAULT CURRENT_TIMESTAMP, and you can just ignore that column when inserting - it will automatically be filled with the current time. You will need to specify the columns you're inserting to in order to skip a column:
INSERT INTO blogentry( column1, column2 ) VALUES( column1value, column2value )
Finally, you NEED to sanitize your inputs. Preferably using prepared statements and PDO (http://php.net/manual/en/pdo.prepared-statements.php), or at least using mysql_real_escape_string.
From the MySQL manual on DATE, DATETIME
The DATE type is used for values with a date part but no time part.
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The
supported range is '1000-01-01' to '9999-12-31'.
This means you have to insert the dates in YYYY-MM-DD format. You are using date('d-m-Y h:m:s') format. Change that to date('Y-m-d') and it should insert correctly.
If you want the time as well, then you need to change the column datatype to DATETIME and then insert using the format date('Y-m-d H:i:s').
As other mention, you can use an INT column type instead and store a Unix timestamp which is stored in UTC so it is more portable. You can then easily manipulate the timestamp to output the date any way you would like.
Try just storing a strtotime() result. It creates a unique timestamp, which can then be parsed however you need it in the future.
You might need to give the timestamp to the date function:
date('d-m-Y h:m:s', strtotime('now'))
Also, to do a standard datetime format:
date('Y-m-d H:i:s', strtotime('now'))
I want to save the date and time from PHP to SQL. Here is the SQL statement to insert new record (found in a method within a class):
INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
value (:headline, :text, :date, :rating, :product_id, :username)
And in my .php page, I call the current date and time using $_SERVER['REQUEST_TIME']. But still I'm getting the error "Incorrect datetime value". What can I use to get the date?
Your timestamp can be generated:
$timestamp = date('Y-m-d H:i:s');
This should mimic the mysql timestamp and datetime formats.
Assuming that the mysql has its timestamp synchronized with the php server in question, you can also just use the mysql current timestamp functions:
NOW() or CURRENT_TIMESTAMP or CURRENT_TIMESTAMP()
Does it have to be the exact request time? You could make your life easier and simply use:
INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
value (:headline, :text, now(), :rating, :product_id, :username)
MySQL inserts the current date as soon your entry is written to the table.
it is only a guess, but $_SERVER['REQUEST_TIME'] returns a float, not a valid datetime format.
If you need the current time you can do it like that:
INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
INSERT INTO tbl_reviews ('$headline', '$text', CURDATE(), '$rating', '$product_id', '$username');
date_default_timezone_set('US/Eastern');
$cur_date=date("Y-m-d");
You can use SQL's own CURRENT_TIMESTAMP value to get an automatically formatted timestamp.
As for $_SERVER['REQUEST_TIME'], you can just use time() or microtime() instead.
As mentioned, REQUEST_TIME, as well as time() and microtime() return a UNIX timestamp, which is basically the amount of seconds that have passed since the UNIX epoch, which is not the same format as a DATETIME field expects.
I have a MySQL database. All the fields, I assign and I have a datestamp for my date field.
it automatically generates YYYY-MM-DD HH:MM:SS like this 2011-11-21 21:31:37
However, I would like it to do so in two diffrent columns:
A date field with YYYY-MM-DD or 2011-11-21
A time field with HH:MM:SS or 21:31:37
This is my insert php code
$sql= "INSERT INTO `db`.`table` (`id` ,`fkid` ,`paid` ,`date`)
VALUES (NULL, '$userid', '0', CURRENT_TIMESTAMP);";
I have tried CURRENT_DATESTAMP and it does not work.
The 2nd part of the question is: how to I make the table so it works with the proper code? Should the structure of the of the field be type text, or date?
I would not recommend splitting your timestamp into separate date and time columns. Instead, it is easiest to use a DATETIME column, and query it for its date and time portions using the MySQL functions DATE() and TIME():
SELECT DATE(`date`) AS d, TIME(`date`) AS t FROM db.dable;
When inserting, you can use the NOW() function to set the current timestamp. `CURRENT_TIMESTAMP() is a synonym for NOW().
$sql= "INSERT INTO `db`.`table` (`id` ,`fkid` ,`paid` ,`date`)VALUES (NULL , '$userid', '0', NOW());";
How do I insert the current date to my database? I have a column called date to put it on.
I want to insert it at the same time I insert this:
$sql="INSERT INTO `Lines` (Text, PID, Position)
VALUES
('$text','$pid','$position')";
Is there a way to automate it in PHPMyAdmin or it's the same to do it this way? Thanks
If the table definition has the timestamp column default set to CURRENT_TIMESTAMP, you actually don't have to do anything at all. Otherwise, NOW() and CURRENT_TIMESTAMP will work, as in:
INSERT INTO t1 (timestamp_column) VALUES (NOW());
There is a difference between CURRENT_TIMESTAMP and NOW() but it's probably too small to matter to you.
phpMyAdmin seems like it has CURRENT_TIMESTAMP as an option when creating a new column.
INSERT INTO `Lines` (`date`) VALUES (NOW());
Depending on your requirement, you can also do this
$date=date('d.m.y h:i:s');
And then insert $date. I mean if you only want to view the date & time. Otherwise i also recommend time().
Otherwise... if you're using an integer, as is common in PHP, just use time() and insert it's value the same way you inserted the other variables, or use MySQL's UNIX_TIMESTAMP()
The best way to store timestamps is as UNIX timestamp integers in GMT / UTC. This allows you to always know the exact time no matter where you, your server, or your users are located. A bonus is that you can allow your users to set their timezone and display times meaningful to them.
$sql = "INSERT INTO `Lines` (`timestamp`) VALUES ('" . time() . "')";
or
$sql = "INSERT INTO `Lines` (`timestamp`) VALUES ( UNIX_TIMESTAMP() )";
Be careful if you choose to use NOW() or CURRENT_TIMESTAMP as they are managed by the database server and it's settings. If the server your site is hosted on is in one time zone and you move to another host in another timezone all of your timestamps will be incorrect. Using Unix integers will add a little extra effort wherever you application deals with times but it gives you the most accuracy and the most flexibility.