Loko
Loko

Reputation: 6679

PHP inserting the type datetime into sql

I have made a sql row as type: datetime.

The input for datetime should be like: 2013-02-02 10:13:20

You get the drill like: 0000-00-00 00:00:00

Now In php I use date("Y-m-d H:i:s");(current date and time) to insert it into my database. There are other variables as well. Those variables get inserted,but the datetime row stays: 0000-00-00 00:00:00

I first got this code when everything except the date worked:

$resultaat = $mysqli2->query("INSERT INTO questions  (title, description, username, date_made) VALUES ('" . $title . "','" . $description . "', '".$username ."','".date("Y-m-d H:i:s")."')");

but all the information in the databases will get "" around them.(Which could have caused the date to jump to 0000-00-00 00:00:00

Now when I try to insert again with other information, it wont even insert anymore. My problems:

EDIT:

Nvm I lost the "" It wasn't the problem that cause the insert to fail at the second try. - Why wont it insert in it anymore after I inserted once?

Now these aren't really different questions because it's about the same problem but here's my code and yes I know SQL Injection, I'll fix it later:

if (isset($_POST['title'])) {
$alles_goed=true;
$description=$_POST['description'];
$title=$_POST['title'];
$username=$_SESSION['username'];

if ($title=''){ 
$alles_goed=false;
echo'title is empty';
}

if($alles_goed==true){
    $resultaat = $mysqli2->query("INSERT INTO questions  (title, description, username, date_made) VALUES ('" . $title . "','" . $description . "', '".$username ."','".date("Y-m-d H:i:s")."')");

}
}

Upvotes: 3

Views: 20071

Answers (2)

sskoko
sskoko

Reputation: 839

Try this:

$a=date("Y-m-d H:i:s");
if (!$resultaat = $mysqli2->query("INSERT INTO questions  (title, description, username, date_made) VALUES ('$title','$description','$username','$a')"))
{
   printf("Errormessage: %s\n", $mysqli2->error);
   exit;
}

and check if there is any error produced.

As to why is inserting it only once, you might have unique field.

Upvotes: 5

Just use a now() on MySQL

$resultaat = $mysqli2->query("INSERT INTO questions  (title, description, username, date_made) VALUES ('" . $title . "','" . $description . "', '".$username ."',now()");

Upvotes: 5

Related Questions