Thursday, 15 August 2013

php - Validating Multiple Dynamically Created Fields -



php - Validating Multiple Dynamically Created Fields -

i have form dynamically created fields 1 of file input field.

for non-dynamically created input fields, utilize validate on server side:

if(isset ($_post['submitform'])) { $error = array(); foreach($_post $key => $value) { $data[$key] = filter($value); } if(empty($data['randominputfield'])) { $error[] = "<p>input here</p>"; } $target = "path/to/folder/"; $fileinput = ($_files['fileupload']['name']); $filebasename = substr($fileinput, 0, strripos($fileinput, '.')); $fileextension = substr($fileinput, strripos($fileinput, '.')); $filesize = $_files["fileupload"]["size"]; $fileformats = array('.png','.jpeg','.jpg','.gif'); if (in_array($fileextension, $fileformats) && ($filesize <= 350000)) { // rename file $fileinputnewname = md5($filebasename) . $fileextension; if (file_exists("path/to/folder/" . $fileinputnewname)) { $error[] = "<p>a file name exists</p>"; } else { $filemove = move_uploaded_file($_files["fileupload"]["tmp_name"], "path/to/folder" . $fileinputnewname); } } elseif (empty($filebasename)) { $error[] = "<p>please select file upload</p>"; } elseif ($filesize > 350000) { $error[] = "<p>files should not exceed 350kb</p>"; } else { $error[] = "<p>only files extensions ". implode(', ',$fileformats)." allowed</p>"; unlink($_files["fileupload"]["tmp_name"]); } if(empty($error)) { //perform database insertion } }

and works beautifully.

but want give user chance of adding infinite number of fields (i accomplished using jquery) can upload more 1 set of info (i.e. random input , file) @ same time , want validate , proceed store each set of info in database. ideas?

i utilize approach dynamic number of inputs...

first create jquery append each info set on form way:

//on each click @ "plus" button append 2 inputs these ones <input name="dynamicfields[filedescription][]" placeholder="file description..."><br> <input type="file" name="dynamicfields[file][]">

the @ server side you'll in $_post var 2 arrays 1 file descriptions , 1 files. can utilize method grouping info sets:

public static function parseinputtable($inputtable) { $result = array(); foreach ($inputtable $columnname => $columnvalues) { foreach ($columnvalues $rowindex => $columnvalue) { $result[$rowindex][$columnname] = $columnvalue; } } homecoming $result; }

so example:

var_dump(parseinputtable($_post['dynamicfields']));

outputs

array(3) { [0] => array(2) { ['filedescription'] => string(4) "foo1", ['file'] => /*file 1*/ }, [1] => array(2) { ['filedescription'] => string(4) "foo2", ['file'] => /*file 2*/ }, [2] => array(2) { ['filedescription'] => string(4) "foo3", ['file'] => /*file 3*/ } }

php mysql validation

No comments:

Post a Comment