gpt4 book ai didi

php - 将数据内爆回单个单词

转载 作者:行者123 更新时间:2023-11-29 10:34:14 26 4
gpt4 key购买 nike

我已经内爆了这些数据。

$fruit = implode(", ",$_POST["fruit"]);

我将这些数据存储在 mysql 表中。表格行看起来像这样:

ID: 1
UserID: 5
chosen: Apple, Banana, Orange

我意识到像这样存储数据是非常愚蠢的,并且希望我的数据以这种方式存储:

ID: 1
UserID: 5
Fruit: Apple

ID: 2
UserID: 5
Fruit: Banana


ID: 3
UserID: 5
Fruit: Orange

问题是我有大约 100 条记录以这种方式存储,我想听听是否有一种方法可以用 PHP 循环出旧数据并将其插入新表中,使其看起来像上面的示例,所以我不必手动更改所有记录?

最佳答案

类似这样的事情应该可以解决问题(其中 $mysqli 是您的连接):

if($result = $mysqli->query("SELECT * FROM `table1`")){ // select all data from the current table (where the imploded data is)
if($stmt = $mysqli->prepare("INSERT INTO `table2` SET `UserID`=?, `Fruit`=?")){ // prepare insertion in the new table (I'm assuming that the ID column is autoincremented)
while($data = $result->fetch_array()){ // get data as an array
$fruits = explode(', ', $data['chosen']); // explode the fruits
foreach($fruits as $fruit){ // loop through the fruits
$stmt->bind_param('is', $data['UserID'], $fruit); // bind data
$stmt->execute(); // insert row
}
}
}
}

我没有实际测试过,但你可以尝试一下。

关于php - 将数据内爆回单个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46777798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com