March 7, 2012

How to combine both array and insert into database php

Question by vvr

if only one array is there for example

$values = array(x, y, z);

i am adding them into database like this

    foreach ($values as $value)
    {
        $insertFunction = addValues($value);
    }

my arrays:

$array1 = Array ( 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 );

$array2 = Array ( fb1, or1, fb2, or2, fb3, or3, fb4, or4, fb5, or5 );

But i want both array to combine and insert them into database.
How can i do this please help me

Updated:

When i am printing the POST values i am getting out put like this

Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 2 [4] => 1 [5] => 2 [6] => 1 [7] => 2 [8] => 1 [9] => 2 )

Array ( [0] => fb1 [1] => or1 [2] => fb2 [3] => or2 [4] => fb3 [5] => or3 [6] => fb4 [7] => or4 [8] => fb5 [9] => or5 )

when i tried with array_merge my out put is like this

Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 2 [4] => 1 [5] => 2 [6] => 1 [7] => 2 [8] => 1 [9] => 2 [10] => fb1 [11] => or1 [12] => fb2 [13] => or2 [14] => fb3 [15] => or3 [16] => fb4 [17] => or4 [18] => fb5 [19] => or5 ) 

How to insert them in separate columns in a table $array1 and $array2

my database table is like this

1.id
2.username
3.network_id

id is primary key
network_id values coming in array1
username values coming in array2

Answer by Ofir Baruch

EDIT:

After you mentioned seperated columns I think I understand what you’re looking for:
I’m assuming that array1 and array2 are in the same size.

for($i = 0; $i < count($array1); $i++)
{

  $array2[$i] = (int)$array2[$i]; //"validating" the username (an integer)
  mysql_query("INSERT INTO yourTableName (`username`,`network_id`) VALUES('".$array2[$i]."','".$array1[$i]."')");
}

Result:

tblName:

username: 1 2 1 …

network_id: fb1 or1 fb2 …

Is that what you were looking for?

Ignore this and merging:

    $combined = array_merge($array1 , $array2);

   //$combined = Array ( 1, 2, 1, 2, 1, 2, 1, 2, 1, 2,fb1, or1, fb2, or2, fb3, or3, fb4, or4, fb5, or5 );

Answer by Starx

You can use array_merge(), function to merge multiple array into one.

$arrays = array_merge($array1 , $array2);
foreach ($arrays as $value)
{
    $insertFunction = addValues($value);
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!