As a new programmer I'm having trouble figuring out how to exactly code this situation. I've taken some of the solutions via stackoverflow but this one doesn't seem to work as I thought it would. I have a tag that correctly puts in one selected item but if I put in two or three it gives me the numbers. I.e. if I selected 3 options with id's 3, 5 and 8 it turns into 358 instead of creating a many-to-many catalog relationship of 3-3, 3-5, 3-8.
The purpose is that the form is creating a new character that can gain several disadvantages. These disadvantages are then linked to the new characters unique id.
$query2 = implode ( "",$_POST['did']);
$sql="INSERT INTO player_disadvantage
(disadvantageid,characterid)
VALUES ('".$query2."',LAST_INSERT_ID())"
;
<tr>
<td>Disadvantages</td>
<td>
<?php
$result = $mysqli->query("SELECT * FROM disadvantages");
echo '<SELECT multiple="multiple" id="did" name="did[]">';
while($row1 = $result->fetch_assoc()) {
$disadvantages = $row1['name'];
$disadvantagesid = $row1['did'];
$disadvantagescost = $row1['cost'];
echo "<option value='".$disadvantagesid."'>". '+' . ' ' . $disadvantagescost . ' ' . $disadvantages . "</option>";
}
echo '</select>';
?>
</td>
My only guess is to find a way to move the code so that it puts the LAST_INSERT_ID() with every disadvantage id. I'm not sure how to code it.
Try this:
$values = implode(',', array_map(function($x) {
return "('" . mysql_real_escape_string($x) . "', LAST_INSERT_ID())"; },
$_POST['did']));
$sql = "INSERT INTO player_disadvantage (disadvantageid, characterid) VALUES $values";
This creates a query that looks like:
INSERT INTO player_disadvantage (disadvantageid, characterid)
VALUES ('3', LAST_INSERT_ID()),
('5', LAST_INSERT_ID()),
('8', LAST_INSERT_ID())
to add multiple rows.