I'm using PostgreSQL for my tests and I've set one column start_dte
as Date data type while scheduled_time
and sla_time
are both Time data type. I've created a form that would allow me to insert new record.
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<table border="0" cellspacing="10">
<tr>
<td>RID:</td> <td><input type="text" name="newrid" value=""></td>
</tr>
<tr>
<td>Day:</td> <td><input type="text" name="newday" value=""></td>
</tr>
<tr>
<td>Scheduled Time:</td> <td><input type="text" name="newsched" value=""></td>
</tr>
<tr>
<td>SLA Time:</td> <td><input type="text" name="newsla" value=""></td>
</tr>
<tr>
<td>Start Date:</td> <td><input type="text" name="newsd" value=""></td>
</tr>
<tr>
<td><INPUT TYPE="submit" VALUE="Save" NAME="submit"></td>
</tr>
</table>
The PHP Code right below it is this:
<?php
if(isset($_POST['submit'])) {
$rid = $_POST['newrid'];
$day = $_POST['newday'];
$scheduled_time = $_POST['newsched'];
$sla_time = $_POST['newsla'];
$start_dte = $_POST['newsd'];
$data = $dbh->prepare("INSERT into meta_auto_reports.frequency values ($rid, '$day', $scheduled_time, $sla_time, $start_dte)");
$data->execute();
echo "<h2>Inserted Successfully</h2>";
$data = null;
}
?>
This shows an error upon submit:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42804]: Datatype mismatch:
So I'm wondering what's the proper way of formatting user input in a way that postgresql would accept. The Columns are Nullable as well, which means an empty field left blank by a user would have to place NULL
upon insertion.
Few comments about this code:
Form values should be stored in an array:
<td>RID:</td> <td><input type="text" name="form[newrid]" value=""></td>
<td>Day:</td> <td><input type="text" name="form[newday]" value=""></td>
This way, it is easier to manipulate them:
$form_data = $_POST['form'];
I would strongly suggest you use a library to validate and clean the data submitted by end users (symfony/validator does this job but there are many other libraries).
Now, the database part. Data sent to the database need to be escaped to protect you application against SQL injection. Using a prepared statement is a way to pass data as parameters:
$stmt->prepare("INSERT into meta_auto_reports.frequency values (:id, :day, :scheduled_time …)");
$stmt->execute($form);
Using PDO directly does mix different concerns in the same layer of code (the how and the what). Using a library to handle database connectivity and queries is a good idea. (Pomm if specifically using Postgres or any DBAL or ORM if you want database abstraction).