2

Array $ids contains:

Array ( [0] => 25 [1] => 29 [2] => 30 [3] => 34 )

How do I insert each key as a row in column ID?

ID |
25
29
30
34

So far I did this, I don't know if it's possible to stick it in the query though:

$x = 0;
while($x < 6) {
echo "values ('" . $follower . "','" . $ids[$x] . "')";
$x++;
}
2
  • Where do you stuck? What have you tried so far? Commented Nov 21, 2011 at 5:26
  • Yes, sorry. I'm trying to make a loop that echoes the Values and see if that can be integrated in the query. I don't know if it's possible. I add it in the question. Commented Nov 21, 2011 at 5:35

4 Answers 4

4

it's as simple as that:

foreach ($ids as $k => $v) {
     mysql_query("insert into TABLE_NAME(ID) values($v)");
}

and for you second question:

foreach ($ids as $k => $v) {
    if($k!=0){
        mysql_query("insert into TABLE_NAME values($v)");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

this will execute query multiple time, but my solution will executed only once for multiple value.. stackoverflow.com/questions/8207628/…
1
foreach($ids as  $id=> $val){
mysql_query("insert into table(id,value) values($id,$val)",$cn);
}

Comments

1
  • you iterate through the array: foreach ($arr as $key => $value) {
  • on each iteration you create an SQL query $sql = "INSERT INTO table (id) VALUES ($value)"; - of course you will mysql_real_escape the value of $value before doing this
  • then execute the query: mysql_query($sql)

Comments

1

you may use

$sql = "";
foreach($ids as  $id=> $val){
if(empty($sql)){
$sql = "insert into table(follower,value) values( $follower,$val)";
}else{
$sql.=",($follower,$val)";
}
}
mysql_query($sql);

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.