2
votes

I have 1 row having 5 form fields. User can add/remove rows. Its repeatable row. Now i want to store these fields into database with PDO php.

For normal values i am using this code but i am confused for repeater field.

$data = array(
    'bill_no' => trim($_REQUEST['bill_no']),
    'from_name' => trim($_REQUEST['from_name']),
    'to_name' => trim($_REQUEST['to_name']),
    'date' => trim($_REQUEST['date_bill']),
    'mr_or_ms' => trim($_REQUEST['mr_or_ms']),
);

if($crud->InsertData("bill",$data)) {
    header("Location: add-bill.php");
}

Insert Function:

public function InsertData($table,$fields) {
    $field = array_keys($fields);

    $single_field = implode(",", $field);
    $val = implode("','", $fields);

    try {
        $query = $this->db->prepare("INSERT INTO ".$table."(".$single_field.") VALUES('".$val."')");

        $query->execute();
        return true;
    } catch(PDOException $e) {
        echo "unable to insert data";
    }
}

Please help me to insert fields. Thanks

2
You are wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Specially since you're not escaping the input data at all. - Magnus Eriksson

2 Answers

1
votes

Change the names of your form fields, add [] to the end to get PHP arrays. For example change bill_no to bill_no[]. Something like this:

foreach($_REQUEST['bill_no'] as $row_number => $row_content){
   $data = array(
    'bill_no' => trim($_REQUEST['bill_no'][$row_number]),
    'from_name' => trim($_REQUEST['from_name'][$row_number]),
    'to_name' => trim($_REQUEST['to_name'][$row_number]),
    'date' => trim($_REQUEST['date_bill'][$row_number]),
    'mr_or_ms' => trim($_REQUEST['mr_or_ms'][$row_number]),
  );
  $crud->InsertData("bill",$data);
}

This assumes the browser is not mixing up the order of the fields, so maybe it's better to add unique names to the form fields when adding rows.

Also, there's no input data validation at all, please ensure you are escaping all data properly.

1
votes

I did it with this method.

$total=count($_POST['description']);
for($i=0; $i<$total; $i++){
    $data1 = array(
        'bill_no' => trim($_POST['bill_no']),
        'description' => trim($_POST['description'][$i]),
        'nos' => trim($_POST['nos'][$i]),
        'nos_day' => trim($_POST['nos_day'][$i]),
        'pay' => trim($_POST['pay'][$i]),
        'weekly_off' => trim($_POST['weekly'][$i]),
        'hra' => trim($_POST['hra'][$i]),
        'rs' => trim($_POST['rs'][$i]),
        'ps' => trim($_POST['ps'][$i]),

    );
    $crud->InsertData("bill_details",$data1);
}