donglu1881
2012-08-27 11:40
浏览 52
已采纳

如何将数组值插入数据库表的列?

I have an array with three values red, green and yellow. Now i should

insert red into column3 row1
insert green into column3 row2
insert yellow into column3 row3

How can i do that i tried writing the code

foreach ($output as $value)
{
    echo ($value.'<br>');
    $tstring = implode(',' , $output);
    $insert_col= "UPDATE INTO `5` (B) VALUES ('$tstring')";
    $insert_result = mysql_query($insert_col);
    if ($insert_result)
    { 
        echo ("RECORDED!")|
        exit();
    }
}

but it does not work. it is filling extra rows to the existing table with a value R.

Please help!

图片转代码服务由CSDN问答提供 功能建议

我有一个包含红色,绿色和黄色三个值的数组。 现在我应该

 将红色插入column3 row1 
insert green into column3 row2 
insert yellow into column3 row3 
   
 
 

我怎么能这样做我尝试编写代码

  foreach($ output as $ value)
 {
 echo($ value。'&lt; br&gt;')  ; 
 $ tstring = implode(',',$ output); 
 $ insert_col =“UPDATE INTO`5`(B)VALUES('$ tstring')”; 
 $ insert_result = mysql_query($ insert_col);  
 if($ insert_result)
 {
 echo(“RECORDED!”)| 
 exit(); 
} 
} 
   
 
 

但是 这是行不通的。 它使用值R向现有表填充额外的行。

请帮助!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douhuan6157 2012-08-27 11:52
    已采纳

    if I remember correctly, an UPDATE statement should have a WHERE clause.

    Like:

     UPDATE table SET column_name='value' WHERE condition;
    

    You can find examples at w3schools.

    As for inserting the right value:

    foreach($output as $value){
         $tstring = $value;
         $insert_col = "UPDATE `5` SET B='" . $tstring . "' WHERE insert a condition here";
         $insert_result = mysql_query($insert_col);
    
        if ($insert_result) {
             echo ("RECORDED!") |
        }
    }
    

    You don't want to insert all your array in one row, which means that the implode is useless.

    And I repeat, you need a WHERE clause here. Without it, you'll update all your rows with the same values.

    已采纳该答案
    打赏 评论
  • donglianer5064 2012-08-27 11:45

    You got couple of errors. Looks you forgot to connect to the database and also you exit() after 1st successful insert. So if you got more elements in array, these will not be stored. You may also want to display value of mysql_error(); in case of failure

    打赏 评论

相关推荐 更多相似问题