作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经内爆了这些数据。
$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/
我是一名优秀的程序员,十分优秀!