I have a form which gives the ability for the user to add additional fields form to the form and it selects data from the database for the select/options.
It works ok but not entirely correct and am wondering if somebody wouldn't mind casting an eye on the code to see if can be done in a much cleaner way.
The main issue being that the select isn't sending the correct value across to the action script.
HTML output of the form:
<?php $dashboardId = $_GET['dashboard_id']; ?>
<form action="cm.php" method="POST">
<input type="hidden" name="dashboardId" value="<?php echo $dashboardId; ?>">
<div id="exercises">
<div class="team">
<select name="teamId[]">
<?php
$sql = "SELECT * FROM teams WHERE dashboard_id = $dashboardId";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value="' . $row["team_id"] . '">' . $row["team_name"] . '</option>';
}
}
?>
</select>
<button class="remove">x</button>
</div>
</div>
<button id="add_exercise">add more</button>
<br>
<input type="text" name="memberName">
<br>
<input type="submit" name="submit" value="Create Member" />
</form>
So the above renders out my simple form. The second part the JQuery that handles the facility to add additional select fields.
<script type="text/javascript">
$('#add_exercise').on('click', function() {
$('#exercises').append('<div class="team"><select name="teamName[]"><?php
$sql = "SELECT * FROM teams WHERE dashboard_id = $dashboardId";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value="' . $row["team_id"] . '">' . $row["team_name"] . '</option>';
}
}
?> </select><button class="remove">x</button></div>');
return false; //prevent form submission
});
$('#exercises').on('click', '.remove', function() {
$(this).parent().remove();
return false; //prevent form submission
});
</script>
Now as can be seen it isn't the neatest of solutions combining the jQuery with the Php however I am not sure how else I would separate it out? So what is happening is when I do a var_dump($_POST)
I see that the generated select passes ["teamName"]=> array(1) { [0]=> string(3) "211"
where it should be passing ["teamId"]=> array(1) { [0]=> string(3) "211"
I am fully aware it is open to SQL injection but for now I am just trying to make this little part work.
update - team table scehema