current timestamp generation in php and updating in mysql - php

i want to create a timestamp by which i can know which post is modified when and all. in mysql databse, i made a coloumn called lastmodified, with type as timestamp. now, when i am updating the data in db, i want to update the current timestamp in last modified. how to do so? also could anyone please tell me, if any function exits for comparing these timestamps.
$now = time();
$query = "update storydb set lastmodified = '$now' where story_id = '$story_id'";
mysqli_query($con, $query);

time() returns UNIX Timetamp in integer format e.g. 1223485636.
You want it in 2014-12-10 02:02:36
Use MySQL now() function instead of $now
$query = "update storydb set lastmodified = now() where story_id = '$story_id'";
now() is a MySQL function that returns current Time Stamp (including date).

No, its not unix timestamp that should be used in there, just a normal NOW() should suffice:
$query = "UPDATE storydb SET lastmodified = NOW() WHERE story_id = ?";
$update = $con->prepare($query);
$update->bind_param('s', $story_id);
$update->execute();

To insert current unix timestamp in data base
$time = time();
$qry = 'update db_name' set column_name = $time where condition;
mysql_query($qry);

Related

PHP oci_fetch_all from an Oracle DB converts date value

I'm having issues getting a value from an Oracle DB where the value is converted to a date format I don't want. I'd prefer to have the raw value, or at least know where I can change that converted date format. Curious if anyone could point me in the right direction here.
$conn = oci_connect(ORACLE_DB_USERNAME, ORACLE_DB_PASSWORD, '//' . ORACLE_DB_HOST . '/' . ORACLE_DB_SID);
$sql_query = "SELECT * FROM \"ASSET\".\"NAV\" WHERE sem = '2820' AND ROWNUM = 1 ORDER BY date_time DESC";
$stid = oci_parse($conn, $sql_query);
$row_count = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC);
oci_free_statement($stid);
oci_close($conn);
The data in the DB should come back like:
CREATE_DATE => '23-07-2019 19:30:11'
Except, I get this:
CREATE_DATE => '23-JUL-19'
You are getting dates back in the default format of your database. One thing that you could to is alter the NLS setting of your session to the format that you expect. For this, you can run this command:
alter session set nls_date_format = 'dd-mm-yyyy hh24:mi:ss'
Once this command is executed, all dates will be fetched in this format during the lifetime of your Oracle session.
If you are dealing with timestamp datatype instead of date, then the nls parameter is nls_timestamp_format (and nls_timestamp_tz_format for timestamp with timezone).
Another option is to use to_char() to format the date to the desired format in the query itself:
$sql_query = "SELECT <column list>, to_char(create_date, 'dd-mm-yyyy hh24:mi:ss') create_date FROM ...";

php mysql last visit

I have website where the user can show his last visit to the website every time he logs in.
the type of last_activity column in the database is 'time'.
I made a code that shows the current date and save it in a variable $currentDate
and then set variable $currentDate into last_activity column in the database and update the column every time the user logs in.
but when I test the code I get this result:
your last visit: 00:00:00
the type of last_activity column in the database is 'time'.
here is my code:
<?php
session_start();
include('db.php');
date_default_timezone_set('Asia/Riyadh');
$currentDate = date('m/d/Y h:i:s a', time());
if(isset($_SESSION['Email']) === true)
{
mysql_query("UPDATE `table` SET `lastactivity` = ".$currentDate." WHERE email = '".$_SESSION['Email']."'");
$query = "SELECT * FROM `table` WHERE email = '".$_SESSION['Email']."'";
$run = mysql_query($query);
while($row = mysql_fetch_array($run))
{
$name = $row[1];
$active = $row[10];
echo 'welcome '.$name;
echo 'your last visit '.$active;
;
You should use the type DATETIME or TIMESTAMP to store a datetime value instead of TIME. The TIME datatype has no notion of dates:
The TIME Type
MySQL retrieves and displays TIME values in 'HH:MM:SS' format (or
'HHH:MM:SS' format for large hours values). TIME values may range from
'-838:59:59' to '838:59:59'.
...
Invalid TIME values are converted to '00:00:00'.
Because of that you get
your last visit: 00:00:00
back from the database as your output.
The DATE, DATETIME, and TIMESTAMP Types
The DATETIME type is used for values that contain both date and time
parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD
HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to
'9999-12-31 23:59:59'.
Edit:
TIMESTAMP and in newer MySQL versions DATETIME columns have nice features, i.e. automatic update:
Automatic Initialization and Updating for TIMESTAMP and DATETIME
As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically
initializated and updated to the current date and time (that is, the
current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and
for at most one TIMESTAMP column per table.
Edit 2:
Furthermore produces
$currentDate = date('m/d/Y h:i:s a', time());
no valid format of an DATETIME literal. You could use STR_TO_DATE() to convert your value to DATETIME, but I wouldn't recommend this. Better you change your UPDATE statement using the MySQL function NOW() to:
mysql_query("UPDATE `table` SET `lastactivity` = NOW() WHERE email = '".$_SESSION['Email']."'");
You can format your DATETIME value, while retrieving it from MySQL with DATE_FORMAT() and give this computed column a name:
$query = "SELECT *, DATE_FORMAT(lastactivity, '%m/%d/%Y %h:%i%s %p') as last_activity FROM `table` WHERE email = '".$_SESSION['Email']."'";
$run = mysql_query($query);
while($row = mysql_fetch_array($run))
{
$name = $row[1];
$active = $row["last_activity"]; // access to the column by column name
// ...
Note
I recommend to switch from the deprecated mysql_* functions to PDO or mysqli with prepared statements and placeholders instead of concatenation of an sql statement.

Inserting date sometimes inserts all 0's

i have a column in my database for the date a new record was added, it's set with the following code:
$dateset = date("Y-m-d");
$q = "INSERT INTO appts (date_set) VALUES ('$dateset')";
this is working about 80% of the time, is there any reason that randomly it will add the date as "0000-00-00"?
You should check type of field 'date_set'.
if type is DATE you have to use:
$dateset = date("Y-m-d");
if type is DATETIME you have to use:
$dateset = date("Y-m-d H:i:s");
//It is correct, but database push after time 00:00:00 (but it depends on the settings of the database)
//$dateset = date("Y-m-d");
if type is TIMESTAMP you have to use:
$dateset = time();
Try use sql:
$q = "INSERT INTO appts (date_set) VALUES (NOW())";
I think it would the best decision to use
$q = "INSERT INTO appts (date_set) VALUES (NOW())";
is there any reason that randomly it will add the date as "0000-00-00"?
No.
Either $dateset populated some other way or value got updated to 0's later on.

Within PHP should I use today's date function or curdate() from MySQL?

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();

Mysql/Php - Current date and time

I have a query that I want to update a column with the current date time. The column I want to update is of the type datetime.
How can I get it and set it?
else{ //If the last update is NULL, It must be players first page load. So set datetime equal to NOW
$query = "UPDATE `stats` SET `last_ap_update` = WHERE `member_id` = {$_SESSION['SESS_MEMBER_ID']}";
$queryresult = mysql_query($insertqry);
}
Using NOW() in the query would provide this.
else{ //If the last update is NULL, It must be players first page load. So set datetime equal to NOW
$query = "UPDATE `stats` SET `last_ap_update` = NOW() WHERE `member_id` = {$_SESSION['SESS_MEMBER_ID']}";
$queryresult = mysql_query($insertqry);
}
But if this gets updated anytime the table updates, I would suggest changing the column to TIMESTAMP and this will automatically update to the current time for you anytime that record changes.
else{ //If the last update is NULL, It must be players first page load. So set datetime equal to NOW
$query = "UPDATE `stats` SET `last_ap_update` = '".gmdate("Y-m-d H:i:s")."' WHERE `member_id` = {$_SESSION['SESS_MEMBER_ID']}";
$queryresult = mysql_query($insertqry);
}
You can use any format you want instead of gmdate("Y-m-d H:i:s")
You can use the mysql function NOW() for this, or you can pase the $_SERVER['REQUEST_TIME'] in there so the query gets cached by mysql.

Categories