I am creating a website where the user is asked to input assets into an incident report and the user can add however many assets as they please. When I try to insert the values from the array into the SQL-database it doesn’t let me. I have a connection to the database in an included template so I am only showing the body and relevant code:
<body>
<?php
if (isset($_POST['affected_assets_name'])) {
$additional_asset = $_POST['additional_asset_name'];
var_dump($additional_asset);
foreach ($additional_asset as $asset) {
$insertNewAsset = "INSERT INTO affected_assets (affected_assets_name) VALUES (?)";
$stmtNewAsset = $mysqli->prepare($insertNewAsset);
$stmtNewAsset->bind_param("s", $asset);
$stmtNewAsset->execute();
$stmtNewAsset->close();
}
}
?>
<div class="container">
<h1>Report incident</h1>
<form id="incidentForm" method="post" action="reportincident.php">
<div id="additionalAssetFieldContainer">
</div>
<div>
<button type="button" id="addAssetButton" onclick="addField()">Add Asset</button>
</div>
<input type="submit" value="Report">
<input type="reset" value="Reset">
</form>
</div>
<script>
function addField() {
var container = document.getElementById("additionalAssetFieldContainer");
var newField = document.createElement("div");
var input = document.createElement("input");
input.type = "text";
input.name = "additional_asset_name[]";
input.placeholder = "Additional asset";
newField.appendChild(input);
var removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.textContent = "Remove Asset";
removeButton.onclick = function() {
container.removeChild(newField);
};
newField.appendChild(removeButton);
container.appendChild(newField);
}
</script>
I have tried to dubble check the database and the SQL-statement. I have tried moving the code around to see if that changes anything
Wilma Winther is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.