I am little confuse about to insert the array element in mysql
i have a array as following
$a = array(
'1' => 'a',
'2' => 'b',
'3' => 'c',
'4' => 'd',
'5' => 'e'
'6' => 'f'
);
and i have a table field id1,id2,...may be
id1 id2
a b
c d
e f
can any one help me out with php code.
Thanks to all of you, I really appreciate your effort to give your precious time to fix my situation, finally I had use the array_chunk function to divide my array to multiple sub array same with column no, than I insert the array value by sub key by for each loop.thank you thank you again.
Have a look at this short tutorial. It might be just what you need: http://99webtools.com/how-to-store-array-mysql.php
If the table persists out of 2 columns only, id1
and id2
You could do the following:
$insertVals = ''; //Values go here,
$insertCols = ''; //Column names go here, alternating from id1 to id2
$counter = 0; //Will be used to iterate odd and even.
foreach ($a as $value) {
$insertVals .= "'".$value."',"; //Comma at the end is needed.
if ($counter % 2 == 0) //if even basicly
$insertCols .= 'id1,'; //DB fields do not require quotes, backticks are optional
else
$insertCols .= 'id2,';
$counter++ //Increment counter to cause odd values to occur.
}
//Remove last comma's from both strings.
$insertVals = substr($insertVals, 0, -1); //-1 removes the last char in substr.
$insertCols = substr($insertCols, 0, -1);
$query = "INSERT INTO yourtable ({$insertCols}) VALUES ({$insertVals})";
this should do the trick. Let me know if there are any errors you get since this is written straight out of the head and untested.
Regards, Sidney Liebrand
$a = array(
'1' => 'a',
'2' => 'b',
'3' => 'c',
'4' => 'd',
'5' => 'e'
'6' => 'f'
);
$mysqli = new mysqli("host", "user", "pw", "db");
foreach($a as $insert)
{
$query = INSERT INTO table $insert[1],$insert[2];
$mysqli=mysql_query($query);
}
Try this code: It's untested
This will work for any number of columns.
<?php
$a = array(
'1' => 'a',
'2' => 'b',
'3' => 'c',
'4' => 'd',
'5' => 'e'
'6' => 'f'
);
$col_cnt = 3; // get column count from mysql query.
$temp = array();
for($i=0;$i<$col_cnt;$i++)
$temp[] = ''; //initialize the array. If no value in "a", then empty will inserted
for($t=1;$t<=count($a);$t+=$col_cnt)
{
$ins_arr = $temp; //initialize with empty values
for($j=0;$j<$col_cnt;$j++)
{
$ins_arr[$j] = $a[$t+$j];
}
//
mysql_query("insert into tab1 values(".implode(",",$ins_arr).")");
}
?>
You need to learn a little bit about Database_normalization http://en.wikipedia.org/wiki/Database_normalization. Basicly you create a new table for the array and tie them together with a key.