Tebro
Tebro

Reputation: 166

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.

Upvotes: 0

Views: 7938

Answers (3)

Dhairya Vora
Dhairya Vora

Reputation: 1281

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());

Upvotes: 0

Teena Thomas
Teena Thomas

Reputation: 5239

you need to surround the dates fields with quotes,

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

Upvotes: 3

Landon
Landon

Reputation: 4108

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.

Upvotes: 0

Related Questions