简体   繁体   中英

inserting dates into mysql database

I have a simple form which has a hidden field with a value of:

<?php echo date('Y-m-d'); ?>

When i submit the form via my php processing script everything on the form goes into the database apart from the date.

here is my sql:

$sql = "INSERT INTO wp_reminders (dateofentry, ipaddress, type) VALUES ('$_POST[dateofentry]','$_POST[ipaddress]' ,'$_POST[type]')";

When i echo the date out on the processing page it shows fine.

I have setup the column in my database with the following:

 dateofentry date NOT NULL

Any ideas if there is anything wrong with the above?

Any dates inserted into MySQL must conform to one of the formats that MySQL can parse or it must be converted. ISO 8601 is the preferred format, YYYY-MM-DD HH:MM:SS typically.

If you used PDO:

$sql = "INSERT INTO wp_reminders (dateofentry, ipaddress, type) VALUES (:dateofentry, :ipaddress, :type)";
$statement = $pdo->prepare($sql);
$statement->bindParam(":dateofentry", strtotime(date("Y-m-d H:i:s")), PDO::PARAM_STR);
$statement->bindParam(":ipaddress", $_POST['ipaddress'], PDO::PARAM_STR);
$statement->bindParam(":type", $_POST['type']), PDO::PARAM_STR);
$statement->execute();

Unless you're expecting the forms to take a very long time to process, it might make sense to supply the date at the time of query creation. If not, you can always put that strtotime call into your form instead.

You must use this syntax to create your sql query :

$sql = "INSERT INTO wp_reminders (dateofentry, ipaddress, type) VALUES ('".addslashes($_POST['dateofentry'])."','".addslashes($_POST['ipaddress'])."' ,'".addslashes($_POST['type'])."')";

In your example, you're not wraping your index key with double quote...

And you really shouldn't put a php variable into a string, it's better to concatenate it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM