简体   繁体   English

将逗号分隔的值插入mysql数据库PHP

[英]Insert Comma seperated values to a mysql database PHP

I asked a similar question yesterday but it's not the same. 昨天我问了一个类似的问题,但是不一样。 I have some values that looks like this, and I want to Insert them So that 我有一些看起来像这样的值,我想插入它们,以便

123,567,287,124,172,846,372,187

And I want it to look like this 我希望它看起来像这样

id=123 and SortNumber=1
id=567 and SortNumber=2
id=287 and SortNumber=3

And I want to update a table based on this, so something like this 我想基于此更新表,所以像这样

UPDATE char_
SET SortNumber=1
WHERE id=123
Set SortNumber=2
WHERE id=567

Now, I think I can do something like this 现在,我想我可以做这样的事情

$variable=123,567,287,124,172,846,372,187
$anothervariable=$variable = str_replace(",", "\r\n", $variable); 


$i=0;
$i++;

 mysqli_query(UPDATE char_ SET SortNumber=$i WHERE id=$anothervariable)

But, I'm not sure that the code is 100 correct AND, the variable will be the whole contents and I dont know how I can set a different variable to every line? 但是,我不确定代码是否正确且为100,变量是否为全部内容,我不知道如何为每行设置不同的变量?

Ironically, you can do this directly in MySQL 具有讽刺意味的是,您可以直接在MySQL中执行此操作

update char_
    set sortnumber = find_in_set(id, $variable)
    where find_in_set(id, $variable) > 0;

Note: this will not take advantage of an index on id , so only use this if char_ is small (tens or hundreds of rows) or you do not care about performance. 注意:这不会利用id上的索引,因此仅在char_很小(数十行或数百行)或您不关心性能的情况下才使用此索引。

Suggest you to use explode() and foreach() . 建议您使用explode()foreach()

$variable = '123,567,287,124,172,846,372,187';
$columns = array_filter(explode(',', $variable));
foreach($columns as $key=>$val){
    $sql = "UPDATE char_ SET SortNumber = '".($key + 1)."' WHERE id = " . $val;
    $result = mysqli_query($con, $sql);
    //.....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM