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;
}
}
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
)