I'm designing a small intranet-based time-tracking web app that accepts an unknown number of data "rows" which each consist of 7 form fields. Rows can by dynamically added by the browser.
Can I do better?
Given this (partial) example POST data:
$_POST['project'] =>
Array
(
[0] => PROJECT_CODE_1
[1] => PROJECT_CODE_1
)
$_POST['task']
Array
(
[0] => 21
[1] => 4
)
$_POST['date']
Array
(
[0] => 2012年07月31日
[1] => 2012年07月31日
)
And this iterator:
<?php
$insert_values = array();
for ($i = 0; $i < count($_POST['project']); $i++)
{
$insert_values[] = array(
'entry_id' => null,
'user_id' => $this->session->userdata('user_id'),
'project_id' => $_POST['project'][$i],
'task_id' => $_POST['task'][$i],
'date' => $_POST['date'][$i]
);
}
$this->db->insert_batch('entries', $insert_values);
?>
In general, is this iteration pattern safe and sensible? POST['project']
is a drop-down, is validated and will always be filled.
1 Answer 1
is this iteration pattern safe?
Safe for what? Safe for a database? We can't tell you that! There's no code for your database entry function. What you have here is perfectly safe, but that's excluding any type of insert into a database. To safely protect yourself from SQL injection and other types of security exploits, use prepared queries, validate (sanitize only if needed) incoming data (which includes the username and $_POST['project']
!), and encode any output.
Without your database function, it's difficult to critique your code. There's not too much that be be done wrong in the snippet provided.