I need to update table rows via a form. Sometimes there will be a single row but sometimes multiple, therefore I need the forms to post multidimensional arrays that can easily be looped through and updated in the (Wordpress) database.
I thought the below is how you do it but the $_POST array isnt correct. What do I need to change?
//function to disaply form fields for each row
public function make_form($results) {
$html_fields = '';
$count = 1;
foreach($results as $result) {
if($count != 1){
$html_fields .= '<h4>Row: ' . $count . '</h4>';
}
foreach($result as $field_name => $field_value) {
if ($field_name !='ID'){
$html_fields .= '<p><label for="' . $field_name . '">' . $field_name . '</label><br />';
$html_fields .= '<input type="text" value="' . $field_value .'" id="' . $field_name . '" name="' . $field_name . '[' . $result->ID . ']"></p>';
}
}
$count ;
}
return $html_fields;
}
//function to update database with form data
public function update_row() {
global $wpdb;
$wpdb->show_errors = true;
$table_name = $wpdb->prefix . 'mytable';
echo '<pre>';
print_r($_POST);
foreach($_POST as $id => $values){
$results = $wpdb->update($table_name, $values, array( 'ID' => $id ));
}
}
The array prints out as this:
Array (
[REF] => Array
(
[648] => D10902B-SE
)
[QC] => Array
(
[648] => 1
)
[QCT] => Array
(
[648] => EA
)
[update] => Update )
When I need something more like this:
Array
(
[648] => Array
(
[REF] => D10902B-SE
[QC] => 1
[QCT] => EA
)
[555] => Array
(
[REF] => TESTREF
[QC] => 2
[QCT] => EAFFFFF
)
)
I hope that makes sense...
CodePudding user response:
You could change the order of how you name the input as mentioned in the comment
$html_fields .= '<input type="text" value="' . $field_value .'" id="' . $field_name . '" name="' . $result->ID . '[' . $field_name . ']"></p>';