I have an issue with two foreach loops I am using to insert data into a database.
This is what I currently have:
$to_ord = explode("**", $this->to_ord[$i]);
$i=0;
foreach ($to_ord as $tord) {
$sql3 = "INSERT INTO
temporders (order_description)
VALUES (:order_description)";
$st3 = $conn->prepare ( $sql3 );
$st3->bindValue( ":order_description", $tord[$i], PDO::PARAM_STR );
$st3->execute();
$i++;
}
$qo_ord = explode("**", $this->qo_ord[$i]);
$i=0;
foreach ($qo_ord as $qord) {
$sql4 = "INSERT INTO
temporders (order_description)
VALUES (:order_description)";
$st4 = $conn->prepare ( $sql4 );
$st4->bindValue( ":order_description", $qord[$i], PDO::PARAM_STR );
$st4->execute();
$i++;
}
Basically the code gets to sources of information and inserts them into a table. The second one however doesnt run and I have narrowed it down to being the $i and $++ used because if I remove the $i and $i++ from the first one (the first one wont obviously run with out it) the second script will work, but as soon as i put back in the $i the second one wont work again.
Is there away to get around this? The two arrays wont be the same size.
Any help will be greatly appreciated.
Ian
Well I think you maybe misunderstood the foreach or the array.
I hope I can clarify this, by the below example:
$qo_ord = array(
array( "0 - first value", "0 - second value", "0 - third_value", "0 - fourth value", "0 - fifth value" ),
array( "1 - first value", "1 - second value", "1 - third_value", "1 - fourth value", "1 - fifth value" ),
array( "2 - first value", "2 - second value", "2 - third_value", "2 - fourth value", "2 - fifth value" ),
array( "3 - first value", "3 - second value", "3 - third_value", "3 - fourth value", "3 - fifth value" ),
array( "4 - first value", "4 - second value", "4 - third_value", "4 - fourth value", "4 - fifth value" ),
);
$i=0;
foreach ( $qo_ord as $qord ) {
//$qord is now an element of your array ie. in the first loop => array( "0 - first value", "0 - second value"
echo $qord[$i]."<br>";
$i++;
}
With the code above you going through the array like this:
|X| | | | |
-----------
| |X| | | |
-----------
| | |X | | |
-----------
| | | |X| |
-----------
| | | | |X|
Next example:
// if you want to get the first item just use [0]
foreach ( $qo_ord as $qord ) {
//$qord is now an element of your array ie. in the first loop => array( "0 - first value", "0 - second value"
echo $qord[0]."<br>";
}
With the code above you going through the array like this:
|X| | | | |
-----------
|X| | | | |
-----------
|X| | | | |
-----------
|X| | | | |
-----------
|X| | | | |