sammy
sammy

Reputation: 717

insert date to db with three fields PHP SQL

i need to insert date with three textboxes. textbox for year should have a length of four numbers, two length for month and two for day. and additionally user should not can insert words.

<label for="textfield"></label>
<label for="t1">year</label>
<input type="text" name="t1" id="textfield" width="50" />
<label for="t2">month</label>
<input type="text" name="t2" id="textfield" width="30" />
<label for="t3">day</label>
<input type="text" name="t3" id="textfield" width="30" />

enter image description here

i have a table in my db with date format. how insert these fields to date field of my table?

Upvotes: 0

Views: 125

Answers (2)

Kostas Mitsarakis
Kostas Mitsarakis

Reputation: 4747

You have to check if date exists. Then you can make your query. Also try to use prepare statements to avoid SQL Injection.

$date = $_GET['t1'].'-'.$_GET['t2'].'-'.$_GET['t3'];
if (is_int($_GET['t1']) && is_int($_GET['t2']) && is_int($_GET['t3']) &&  checkdate($_GET['t2'], $_GET['t3'], $_GET['t1'])) {

    //You can use also: 
    //filter_var($_GET['t1'], FILTER_VALIDATE_INT) && filter_var($_GET['t2'], FILTER_VALIDATE_INT) && filter_var($_GET['t3'], FILTER_VALIDATE_INT)

    //Validate your inputs and use prepare statements, this is only for demonstrating purposes
    $sql = "INSERT INTO your_table (date_field) VALUES('$date')";
    //Execute your sql query here
} else {
    echo 'Date does not exist.';
}

Using PDO:

try {
    //Make your connection handler to your database
    $conn = new PDO("mysql:host=".$servername.";dbname=".$database, $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));

    if (is_int($_GET['t1']) && is_int($_GET['t2']) && is_int($_GET['t3']) && checkdate($_GET['t2'], $_GET['t3'], $_GET['t1'])) {

        //You can use also: 
        //filter_var($_GET['t1'], FILTER_VALIDATE_INT) && filter_var($_GET['t2'], FILTER_VALIDATE_INT) && filter_var($_GET['t3'], FILTER_VALIDATE_INT)

        $date = $_GET['t1'].''.$_GET['t2'].''.$_GET['t3'];
        $sql = "INSERT INTO your_table (date_field) VALUES(:date_field)";
        $stmt = $conn->prepare($sql);
        $stmt->execute(array(':date_field'=>$date));

    } else {
        echo 'Date does not exist.';
    }

} catch(PDOException $e) {
    echo $e->getMessage();
    die();
}

Upvotes: 2

skribe
skribe

Reputation: 3615

To restrict what is input into the form in the first place you can use the html5 supported input type "number" along with the maxlength property.

<input type="number"maxlength="4">

But I would do away with the three fields and just use one. And use a field mask to restrict what can be put in. Like this plugin https://igorescobar.github.io/jQuery-Mask-Plugin/ or http://robinherbots.github.io/jquery.inputmask/

Upvotes: 0

Related Questions