hello all i have about 5 array having same no of elements and i want to insert them for each value of array into database like
$array1 has 3 elements a1,a2,a3
$array2 has 3 elements b1,b2,b3
$array3 has 3 elements c1,c2,c3
now i want to insert data into database like field1=a1,field2=b1,field3=c1
and similery for all the values saparete entry will be there
please help me achieve this i know this can be done by foreach loop of php
First count the items in an array.
As you mentioned that there are same number of elements in all the three arrays. Therefore we only need to count number of arrays in any one array. Lets take $array1
here. Use count($array1)
to give element count. Suppose it gives 3
as the count.
Now loop 3 times like below.
for($i = 0; $i < count($array1); $i++){
// QUERY HERE
insert into sometable (field1, field2, field3) VALUES ($array1[$i], $array2[$i], $array3[$i]);
}
You can use SPL's MultipleIterator and prepared statements for that for that.
<?php
$array1 = [ 'a1','a2','a3' ];
$array2 = [ 'b1','b2','b3' ];
$array3 = [ 'c1','c2','c3' ];
$mi = new MultipleIterator;
foreach( array($array1,$array2,$array3) as $a) {
$mi->attachIterator( new ArrayIterator($a) );
}
//$pdo = new PDO( ..., array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
//$stmt = $pdo->prepare('INSERT INTO foo (x,y,z) VALUES (?,?,?)');
foreach( $mi as $rec ) {
//$stmt->execute( $rec );
echo join(', ', $rec), "
";
}
prints
a1, b1, c1
a2, b2, c2
a3, b3, c3
Suppose you have 5 arrays as follows:
$a = array(1,2,3);
$b = array(11,22,33);
$c = array(11,22,33);
$d = array(11,22,33);
$e = array(11,22,33);
create array of fields ;
$fields = array('field1','field2',...);
You can form the data string as follow,
$counter =0;
$str = array();
for($i=0;$i<count($a);$i++)
{
$str []= "$fields[counter] = '$a[$i]'";
$counter++;
$str []= "$fields[counter] = '$b[$i]'";
$counter++;
$str []= " $fields[counter] = '$c[$i]'";
$counter++;
$str []= "$fields[counter]= '$d[$i]'";
$counter++;
$str []= "$fields[counter]= '$e[$i]'";
$counter++;
}
$data = implode(',',$str);
Then execute sql query
insert into 'table_name' $data
Since, same nos of elements are available in each array. So, loop will run for each array for same nos of time.
First, find size of array any array like.
$arraySize=sizeof($arr1);
I assumed $arr1
as Ist array.
Secondly, Now loop it.
for($i=0;$i<$arraySize;$i++)
{
$arr1=$arr1[$i];
$arr2=$arr2[$i];
$arr3=$arr3[$i];
$arr4=$arr4[$i];
$arr5=$arr5[$i];
$InsertQuery="INSERT INTO TableName SET field1='$arr1', field2='$arr2', field3='$arr3',field4='$arr4',field5='$arr5'";
//Execute Your Query Here
}