0

I have a form which can add additional fields by j/s. I am trying to get the values to insert into a single row. Normally you would use a foreach statement. I have tried that for each field and that works but I cannot find how to combine these. There are lots of ways to separate out the arrays but they still appear to need a foreach statement. The form fields look like this

 File Name::&nbsp;<input type="text" class="" name="file_name[]" /> File:: &nbsp;<input type="text" name="files[]" value="" /> 

I have tried a double foreach as follows

if(isset($_POST['file_name'])){ $file_name = $_POST['file_name'] ;//echo $_POST['file_name']; } if(isset($_POST['files'])) {$files = $_POST['files'] ; } foreach($file_name as $file_n){ foreach($files as $file){ $wpdb->insert( 'table', array ('project_ref'=> $reference,'project_name'=>$fil_n,'project_link'=>$file)); }} 

Problem is that if you complete two rows of the fields it inserts 4 rows. Very frustrating

1
  • 1
    You should make it easier for those who might be able to help you by indenting and spacing your code correctly and avoiding typos.
    – migli
    CommentedFeb 17 at 17:33

2 Answers 2

0

foreach loops over a single variable. Here you have two, so using foreach is not the right method. Or you'd have to add a $i index inside the loop to get the second variable. But there's a simpler way:

$total = count($_POST['file_name']); for($i = 0; $i < $total; $i++) { $file_name = $_POST['file_name'][$i]; $file = $_POST['file'][$i]; $wpdb->insert( 'table', array ('project_ref'=> $reference,'project_name'=>$file_name,'project_link'=>$file)); } 
1
  • 1
    perfect thank you very much. This is the first time that I have seen this answer in an understandable way.
    – Ian Young
    CommentedFeb 17 at 17:58
0

To be on the safe side, I'll check that the values are present before the wpdb->insert() :

$total = count($_POST['file_name']); for($i = 0; $i < $total; $i++) { $file_name = $_POST['file_name'][$i] ?? ''; $file = $_POST['file'][$i] ?? ''; if ( !empty($file_name) && !empty($file) ){ $wpdb->insert( 'table', [ 'project_ref'=> $reference, 'project_name'=> $file_name, 'project_link'=>$file ]); } } 

I don't know what the $reference variable corresponds to, but I assume it's declared a little higher up in the code.

2
  • Hi HEXALIX Thank you, I did add that after I had the main statement working- and, yes you are correct $reference is further up the code and is the same for all the inserts on this page.
    – Ian Young
    CommentedFeb 19 at 15:27
  • Glad to have added some security to the code :)
    – HEXALIX
    CommentedFeb 19 at 15:46

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.