-1

I can't get rid of this error Notice: Array to string conversion , when trying to validate array of IDs from form

form code (takes IDs from database):

<tr>
<td><input type="hidden" name="order_id[]" value="<?php echo $result["order_id"]; ?>" class='form-control'></td>

process page:

if(isset($order_nr)) {
    $args = array(
            'order_id' => array('filter'    => FILTER_VALIDATE_INT,
                                'flags'     => FILTER_FORCE_ARRAY)
        );

  $order_id = filter_input_array(INPUT_POST, $args);

  $status = 'something';
  $order->updateOrderStatus($order_id,$status);
}
else {
    $functions->redirect_to("index.php");
}

database page:

public function updateOrderStatus(array $order_id, $status) {
    try {
        $stmt=parent::query("UPDATE " . $this->tableOrders . " SET status=:status WHERE order_id=:order_id");

        foreach($order_id as $id=>$value)
        {
            $stmt->bindParam(":status",$status, PDO::PARAM_STR);
            $stmt->bindParam(":order_id",$value, PDO::PARAM_INT);
            $stmt->execute();
        }
        return true;

    } catch(PDOException $e) {
        echo $e->getMessage();    
        return false;
    }
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
razvan
  • 13
  • 1
  • 3

1 Answers1

0

name="order_id[]" means you are POSTing an array, not a string.

This means, if the submitted value is 1, then the POST array is this:

$_POST['order_id'][0]=1;

But you are treating it like:

$_POST['order_id']=1;

So... if you intend to validate an array of ids, then you will need to iterate the subarray elements and validate them. Or... if you only want validate a single value, then simply remove the [] from your field name.

A demonstration of iterating with array_map():

$_POST['order_id'] = ['3','a','4'];
$order_id = array_map(function($v){return filter_var($v, FILTER_VALIDATE_INT);}, $_POST['order_id']);
print_r($order_id);

Output:

Array
(
    [0] => 3
    [1] => 
    [2] => 4
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • function filter_array_elements($e) { $f = filter_var($e,FILTER_VALIDATE_INT); return $f; } $order_id = array_map("filter_array_elements", $_POST['order_id']); print_r($order_id); $status = 'something'; $order->updateOrderStatus($order_id,$status); and now i have an validated array and code is working – razvan Mar 10 '18 at 11:58
  • @razvan Is my updated answer acceptable? or do you actually want to filter out (remove) elements that are not integers? – mickmackusa Mar 10 '18 at 14:16
  • Your answer is the correct answer for me. Thank you – razvan Mar 10 '18 at 20:54