PHP oci_fetch_all from an Oracle DB converts date value - php

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 ...";

Related

Updating table with form using PHP to MS SQL

I am struggling trying to update a row in an Azure SQL database.
What I am trying to do is to update a row with some input variables along with a fresh datestamp.
If I input the following (for test purposes), my database is updated, but the date is way off:
"UPDATE TABLENAME set COL1 = ".$_POST[VAL1].", COL2 = ".$_POST[VAL2].", COL3 = 2020-03-20 WHERE COL0 = 'VAL0'"
giving me a datestamp looking like this: 1905-06-21T00:00:00.0000000
I have been trying just around a hundred ways of formatting the date() variable, putting it in my SQL statement like this:
"UPDATE TABLENAME set COL1 = ".$_POST[VAL1].", COL2 = ".$_POST[VAL2].", COL3 = ".date()." WHERE COL0 = 'VAL0'"
Needless to say, COL3 is my datestamp column. But I cannot get the database to accept my datestamp formatting. I have tried YYYY-mm-dd xyz1234 in countless variants inside date(), but to no avail.
The database has the following collation set: SQL_Latin1_General_CP1_CI_AS.
Any pointers?
First, about your incorrect date value. It is correct, because when you miss '' around 2020-03-20, SQL Server makes implicit data type conversion. Next example demonstrates this:
Implicit conversion:
DECLARE #date datetime
SELECT #date = 2020-03-20
SELECT #date
SELECT DATEADD(day, 2020-03-20, 0)
Output:
1905-06-21 00:00:00.000
Second, if you want to pass date and time values, just use appropriate format - 'yyyy-MM-dd', 'yyyyMMdd hh:nn:ss' or 'yyyy-MM-ddThh:nn:ss':
"UPDATE TABLENAME set COL1 = ".$_POST[VAL1].", COL2 = ".$_POST[VAL2].", COL3 = '2020-03-20' WHERE COL0 = 'VAL0'"
I don't know how you make your connection to SQL Server, but try to use prepared statements.
Update (Retrieve and send date and time values from and to SQL Server):
Based on driver that you use to connect to SQL Server, you may retrieve date and time values as text or as PHP datetime object (if you use PHP Driver for SQL Server), but you need to send these values as text. In your case values are returned as text. So you need to generate universal datetime value (in 'yyyy-MM-ddThh:nn:ss' for example) as text.
Next example shows some valid and invalid combinations for UPDATE T-SQL statement for your datetime column. It is tested with PHP Driver for SQL Server 4.0.3.
<?php
# Value from database as text
$row['COL3'] = '2019-03-29T11:35:30.0000000';
# Valid statement
$tsql = "UPDATE TABLENAME SET COL3 = '".substr($row['COL3'], 0, 19)."' ";
# Valid statement - date("Y-m-d\Th:i:s") will return current datetime
$tsql = "UPDATE TABLENAME SET COL3 = '".date("Y-m-d\Th:i:s")."' ";
# Invalid statement - date("d-m-Y h:i:s", $row['COL3']) expects int as second parameter,
# generates warning and returns '01-01-1970 12:33:39' as result
$tsql = "UPDATE TABLENAME SET COL3 = '".date("d-m-Y h:i:s", $row['COL3'])."' ";
?>

current timestamp generation in php and updating in mysql

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

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.

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

conversion of datetime datatype to date and time datatype in php/mysql

I am a newbie. I started php coding few days back. I want to copy a "datetime" datatype in php to fields that are of "date" and "time" datatype.
I have kept the field name datetime_info for the datetime value. It exists in try1 table. date is the name of field for "date" datatype and time is the name for "time" datatype. These two exist in try2 table.
Here is what I have written.
$result = mysql_query("SELECT * FROM try1");
while ($row = mysql_fetch_array($result))
{
$result_update = mysql_query("INSERT INTO try2 (date, time) VALUES ('".$row_team['datetime_info']."', '".$row_team['datetime_info']."')");
if (!$result_update)
die('Error: ' . mysql_errno() . mysql_error());
}
The values stored in "try1" table are:
id datetime_info
1 2008-10-02 00:00:00
2 2008-10-09 00:00:00
The expected response should be the date and time stored in respective fields. However, the output is
id date time
2 0000-00-00 00:00:00
3 0000-00-00 00:00:00
Can anyone explain me why and how? I tried a lot of sites but did not find any proper explanation for this. Thank you in anticipation.
Regards,
BasicGem
First of all, you shouldn't have to use PHP to do the hard work here. MySQL is very powerful to do these kinds of tasks on it's own.
Since you are copying all rows from table try1 into try2 (but splitting the datetime column), the following should work:
INSERT INTO
`try2`
SELECT
null, DATE( `datetime_info` ), TIME( `datetime_info` )
FROM
`try1`
What this does is: for every record found in try1 insert the following values into try2:
null means use the auto_increment functionality of the id column in try2 (this is presuming the id column is indeed an auto incrementing primary key field)
DATE( `datetime_info` ) means use the DATE part of the datetime_info column of try1
TIME( `datetime_info` ) means use the TIME part of the datetime_info column of try1
Simply doing mysql_query( $sql ) where $sql is a string that represents above query should suffice then. No need to loop through any results first with PHP.
I was gonna write a PHP solution as well, but others have already done so. I would have suggested this answer.
$result = mysql_query("SELECT * FROM try1");
while ($row = mysql_fetch_array($result))
{
$split = explode(' ', $row_team['datetime_info']);
$result_update = mysql_query("INSERT INTO try2 (date, time) VALUES ('". $split[0]."', '".$split[1]."')");
if (!$result_update)
die('Error: ' . mysql_errno() . mysql_error());
}
Because your taking it into a format and pushing it to fit another one.
Just use explode() and you'll have the 2 parts you need.
list($date, $time) = explode(' ', $row_team['datetime_info']);
Field of type date stores the date information, meaning year, month and day (in that order).
time field, as you might have guessed, stores time information in format of hour:minute:second.
If you take a look at what you did, which is inserting a datetime into date field and time field respectively - MySQL doesn't recognize the format (you are passing the data in the wrong format that's expected for date or time field), hence it stores it as default date value.
You need to parse the output of datetime_info column into the date part and time part and then feed it to mysql.

Categories