简体   繁体   中英

Passing a date from form into MySQL via PHP

I am trying to create a form that adds an event to my calendar by adding it to my MySQL database.

This is the form:

<form action="actions.php?action=addEvent" method="post">
    Titel: <input type="text" name="title"><br/>
    Start tid(YYYY-MM-DD HH:MM): <input type="text" name="startDate"><br/>
    Slut tid(YYYY-MM-DD HH:MM): <input type="text" name="endDate"><br/>
    Beskrivning: <br/>
    <textarea rows="15" cols="10" name="description"></textarea>
    <input type="submit" value="Spara">
</form>

this is the PHP script:

if($_GET['action'] == 'addEvent'){
    $title = mysql_real_escape_string($_POST['title']);
    $desc = mysql_real_escape_string($_POST['description']);
    $startDate = date('Y-m-d H:i:s', strtotime($_POST['startDate'] . ":00"));
    $endDate = date('Y-m-d H:i:s', strtotime($_POST['endDate'] . ":00"));

    mysql_query("INSERT INTO events VALUES (null, '$title', '$desc', $startDate, $endDate);") or header("Location: ./?p=calendar.php&msg=" . mysql_error());
    header("Location: ./?p=calendar.php&msg=Sparat");
}

The MySQL column type is DATETIME. How should i proceed to convert the YYYY-MM-DD HH:MM strings from the form to a type that lets the mysql_query() work. Currently i get the ?msg=Sparat response but no row is entered into the database.

您需要在dates字段周围加上引号,

mysql_query("INSERT INTO events VALUES (null, '$title', '$desc', '$startDate', '$endDate');") or header("Location: ./?p=calendar.php&msg=" . mysql_error());

You can adjust the query to have single quotes around the date. Please read this .

$query_manual = "INSERT INTO tablename (col_name, col_date) VALUES ('DATE: Manual Date', '2008-7-04')";

Also, asking your user to type the date in that format might be a little cumbersome. People expect datepickers theses days. Here's a very simple one I use frequently from jqueryui. You can format the input date as YYYY-MM-DD. If you need to add the time, you can extend the jquery datepicker to be a timepicker .

the date you are receiving is in the correct format. So you need not to change it. You just need to put single quotes around date while using in mysql_query. So you can:

mysql_query("INSERT INTO events VALUES (null, '$title', '$desc', '".$_POST['startDate']."', '".$_POST['endDate']."');") or header("Location: ./?p=calendar.php&msg=" . mysql_error());

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