Insert different date format with php to mysql - php

I have an upload script written in PHP which takes care of data from CSVs and inserts it into each specific table for each CSV that is uploaded.
I need to fix an issue with it not inserting data from a different date format correctly. It needs to cover all date formats and save it like YYYY-MM-DD (2016-09-27), except time.
It looks like this:
Database table:
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USER VARCHAR(50) NOT NULL,
Date DATE,
Time TIME
PHP/MySQL
$stmt = $conn->prepare("INSERT INTO ".$table_name." (User, Date,Time) VALUES (?,?,?)");
$stmt->bind_param("sss", $user, $date,$time);
$user = $data_array[$i][0];
$date = $data_array[$i][1];
$time = $data_array[$i][2];
$stmt->execute();
I've been reading about STR_TO_DATE but I'm not sure where I should use it in this case.

At first i noticed your define the vars after u use them with bind_param()
$user $date $time
Like this:
$user = $data_array[$i][0];
$date = $data_array[$i][1];
$time = $data_array[$i][2];
$stmt->bind_param("sss", $user, $date,$time);
Next:
You can use MySQL Date Format functions.
See: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
With this function you can convert your string date into a valid MySQL date.
VALUES(?,DATE_FORMAT('?','format'),?)
Replace format with the format the data is in
Example from Manual: SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');

Related

PHP/SQL create a date stamp and insert it into database

I'm playing with wordpress $wpdb function.
First of all, I want to create a database table with a column corresponding to the time, so that I can save user actions into this table and know when they did it.
Creating a table:
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id INT NOT NULL AUTO_INCREMENT,
actiontime NOT NULL DATETIME,
PRIMARY KEY (id)
) $charset_collSate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
// execute the query
dbDelta( $sql );
Is this correct? Will it create a DATETIME field that I'm after? I would want a time stamp such that I can get the difference on minute/second intervals.
Inserting in such table:
$wpdb->insert($table_name, array(
'actiontime' => now()
));
Will this work?
I can't check it manually, because I'm developing on a side machine and only have ftp access to live-server and notepad. I can't test anything locally.
I use this php function to get the current value for a MySQL DATETIME field.
/**
* Return current date time.
*
* #return string ISO date time (Y-m-d H:i:s)
*/
function now()
{
return date('Y-m-d H:i:s');
}
There are a few options you could consider,
If you're using plain old PHP and MySQL, you can use the SQL now() function to insert data into a timestamp field like this,
INSERT INTO projects (actiontime) VALUES (now())
Another options would be to use a PHP variable such as, $timestamp = date('Y-m-d G:i:s'); and inserting it in a SQL query:
$timestamp = date('Y-m-d G:i:s');
INSERT INTO projects (actiontime) VALUES ($timestamp);
Hope it helps!
try PHP time() for epoch timestamp

Does MySQL automatically re-format dates inserted in to a column of type DATETIME?

I understand the format of DATETIME in MySQL is YYYY-MM-DD HH:MM:SS.
I am using Bootstrap datepicker which posts a value like 07/30/2014. How can I get that changed to '2014-07-30 00:00:00`?
I don't want the user to see hours etc. but it must be in the string. Is datepicker able to output a string like this?
SQL
$stmt = $dbh->prepare("INSERT INTO bookings (forename, surname, site, badge, start, end) VALUES (:forename, :surname, :site, :badge, :start, :end)");
...
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
yes it is ,but if its a string you should you use STR_TO_DATE() to convert it like this :
$msql ="insert into table (birthdate)value(STR_TO_DATE('$yourdate','%d/%m/%Y'))";
mysql_query($msql);
what i did :
i converted the string $yourdate to a DateTime value.
PS : the %d/%m/%Y should be the format of the date in your string not the one on the server example :
if you had a date like this 22/2/2014 that should work fine, but if you had it like this : 2/22/2014 you should give it this :'%m/%d/%Y'

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.

PHP Insert Query - Date field 0000-00-00

I'm having trouble inserting a record with a date field. No matter what I do, the date field gets stored as '0000-00-00'. The value comes into the php script as a string in this format:
'9/13/2013'. I'm converting to a date using strtotime, then trying to insert the record. Here's the code. Why can't I get this to work? Thanks!
$my_date = strtotime($_POST['d']);
//die(date("Y-m-d", $my_date)); //<--outputs just fine if I uncomment this
$sql = "INSERT INTO locations (id, my_date) VALUES ('$id', '$my_date')";
$result = mysql_query($sql);
I'm converting to a date using strtotime
strtotime returns a unix timestamp (integer), not a date string. You can format it for MySQL before inserting with the date function:
$my_date = date('Y-m-d H:i:s', strtotime($_POST['d']));
Alternatively, you can use the DateTime class for this purpose.

Incorrect datetime value: '31-01-2013' for column 'user_date' at row 1

$query_insert = "INSERT INTO users (user_name, user_pass, user_email, user_date, user_level, user_posts)
VALUES(?,?,?,?,?,?)";
$insert = $mysqli->prepare($query_insert);
$insert->bind_param("ssssii", $username, $password_enc, $email, $date, $level_start, $post_start);
$insert->execute();
$date = date('d-m-Y');
Those are the related parts. The only thing is...when i execute this it doesnt add to the table
I had a look around and someone said to have $insert->error; so I put that in and this came up
Incorrect datetime value: '31-01-2013' for column 'user_date' at row 1
Anybody able to help?
It has to be 2013-01-31, i.e. date('Y-m-d')
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html
when inserting value on date data type, it should be on the following format yyyy-MM-dd, so in your example date, it should 2013-01-31.
Don't worry about the pattern of dates when saved on the database. Leave it as is. If you are concern about the formatting, then you can do it during your projection of the data by using such function called DATE_FORMAT.
DATE_FORMAT()

Categories