内爆数据回到单个单词

时间:2017-10-16 19:33:44

标签: php mysql sql loops insert

我发现了这些数据。

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

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

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条theese记录,并想听听PHP是否有办法循环旧数据并将其重新插入新表中,使其看起来像上面的例子所以我不必手动更改所有记录吗?

1 个答案:

答案 0 :(得分:1)

这样的事情可以解决问题($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
            }
        }
    }
}

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