0

I have problem on Inserting array values into db table...pls help me to solve this problem...thanks in advance...

$array1=([0]=>val1,[1]=>val2,[2]=>val3);
$array2=([0]=>val1,[1]=>val2,[2]=>val3);
$array3=([0]=>val1,[1]=>val2,[2]=>val3);

INSERT INTO table1 (id,date,col1,col2,col3,col4) VALUES (1,now(),'$array1','$array2','$array3',50); 
5
  • 2
    Use foreach loop. Commented May 21, 2014 at 10:24
  • Do you want the field to store a whole array or just one row per element? Commented May 21, 2014 at 10:25
  • if you want to store array you can implode elements in string, and when you need to read them later use explode. Commented May 21, 2014 at 10:27
  • i want to add one row per element.... Commented May 21, 2014 at 10:36
  • you cannot insert an array directly into a table. You need to use a foreach to iterate through all the elements of the array Commented May 21, 2014 at 10:37

3 Answers 3

1

You may try like this, (this is just an example)

foreach($array as $row){
  $query="INSERT INTO 
  table1 (id,date,col1,col2,col3,col4)
  VALUE
  (1,now(),".$row['yourfieldname'].",".$row['yourfieldname'].",".$row['yourfieldname'].",50)";
}
Sign up to request clarification or add additional context in comments.

Comments

0

INSERT INTO table1 (id,date,col1,col2,col3,col4) VALUES (1,now(),'$array1[0]','$array1[1]','$array1[2]',50);

Where the brackets ([]) indicate which array position you want to insert.

1 Comment

i used this format using for loop it's not working...it adds 'A,r' in db table
0

if you want to insert in one row use implode() like

$arr1 = implode(',', $array1)
$arr2 = implode(',', $array2)
$arr3 = implode(',', $array3)

$sql = "INSERT INTO table1 (id,date,col1,col2,col3,col4) VALUES (1,now(),'$arr1','$arr2','$arr3',50)"; 

else you need to use for() or foreach()

for($i =0; $i <=count($array1); $i++){
  $query="INSERT INTO 
  table1 (id,date,col1,col2,col3,col4)
  VALUE
  (1,now(),".$row[$i].",".$row[$i].",".$row[$i].",50)";
}

For forech you can use @sagar's answer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.