我掌握了这些数据。

$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条theese记录,想知道是否有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/

10-12 17:34
查看更多