I have this data i imploded.
$fruit = implode(", ",$_POST["fruit"]);
I stored this data in a mysql table. The tablerow looks something like this:
ID: 1
UserID: 5
chosen: Apple, Banana, Orange
i realised it pretty stupid to store the data like this and rather want my data stored this way:
ID: 1
UserID: 5
Fruit: Apple
ID: 2
UserID: 5
Fruit: Banana
ID: 3
UserID: 5
Fruit: Orange
The problem is i have like 100 of theese records stored this way and wanna hear if there is a way with PHP to while loop out the old data and INSERT it back into a new table to make it look like the above example so i dont have to change all the records manualy?
Something like this should do the trick (where $mysqli
is your connection):
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
}
}
}
}
I didn't actually test it, but you can try it out.