Domanda

The below piece of code isn't working the way it is supposed to

$t = date('Y-d-m H:i:s',time());
$query = "INSERT INTO time VALUES('$t')";
if(mysql_query($query))
echo "Date and Time are added";

I have created a table named time with only one column now and DATETIME as datatype. Even though the PHP script executes successfully in the browser by printing "Date and Time are added".

The database isn't updating the way it is supposed to be. Rather than the current time, it gets initialized to default value.

Do suggest the way to rectify the problem.

È stato utile?

Soluzione

You can use NOW()

$query = "INSERT INTO `time` (`now`) VALUES (NOW())";

Altri suggerimenti

Change the value of $t from

$t = date('Y-d-m H:i:s',time());

to

$t = date('Y-m-d H:i:s');

Even better method would be to write your insert query like this:

   $query = "INSERT INTO `time` VALUES ('".date('Y-m-d H:i:s')."')";
<?php

/* YOU NEED TO ESTABLISH FIRST A CONNECTION */

$con=mysqli_connect("Host","Username","Password","Database"); /* REPLACE THE NECESSARY HOST, USERNAME, PASSWORD, AND DATABASE */

if(mysqli_connect_errno()){

echo "Error".mysqli_connect_error();
}

$t = date('Y-d-m H:i:s');
$query = mysqli_query($con,"INSERT INTO time (now) VALUES ('$t')");
echo "Date and Time are added";

?>

Try with this format

$t = date('Y-m-d H:i:s');
$query = "INSERT INTO time (now) VALUES('$t')";
if(mysql_query($query))
echo "Date and Time are added";

OR

$query = "INSERT INTO time (now) VALUES(NOW())";
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top