在循环中检查错误并执行查询?

I need to be able to check whether all elements of an array are valid before doing the queries, if I do it like this:

$arr = array(5, 3, 'test', 23, 9);
$query = $members->prepare("insert into mytable(a) values(:a)");

foreach ($arr as $val) {
    if (is_int($val)) {
       $query->execute(array(':a'=>$val));
    }
}

I only want to insert the values in the array into the database if all of them are ints, but it inserts the first two values before it gets to 'test' in the array. This is just a random example I made up for the problem that I'm having.

What would be the best way to do this?

There is two ways to handel this:

1) loop through all the values and validate it first ( you really should allays validate data that isnt controlled).

2) If your using PDO/INNOdb start a transaction run that loop and on the fail of the validation rollback and break out of the loop.

eg.

$db->beginTransaction();
$arr = array(5, 3, 'test', 23, 9);
$query = $members->prepare("insert into mytable(a) values(:a)");
$success = true;
foreach ($arr as $val) {
    if (is_int($val)) {
       $query->execute(array(':a'=>$val));
    } else {
      $success = false;
      $db->rollback();
      break;

    }
}

if($success) {
 $db->commit();
}

I only want to insert the values in the array into the database if all of them are ints

when you need to check an array, a loop is always your friend

$fault = 0;
foreach ($arr as $val) {
    if (!is_int($val)) {
        $fault = 1;
        break;
    }
}

How about http://php.net/manual/en/function.array-filter.php

Example:

$arr = array(5, 3, 'test', 23, 9);
$nicearr = array_filter($arr, "getNumbersOnly")

function getNumbersOnly($var)
{
    return is_int($var);
}

Then just use $nicearr for your queries/loop, as you can be certain they're all integers.