0

I'm having some issues submitting an HTML form. The form allows the user to add skills to the HTML page using a button. These newly created skills then need to be inserted into the database. The problem is, I can only insert one skill at a time. The skills are entered as checkboxes and all checked skills should be entered in the database. I think my issue is that each checkbox that is created dynamically shares the same $skill_name variable, but this is not an issue when I grab existing skills from the database to display. I added some ajax to try and save each skill in a post statement as they are created, but it doesn't help when I actually go to insert. The INSERT statement looks something like this:

if(!empty($_POST["backend"])){

    $backend = $_POST["backend"];


    $sql2 = "INSERT INTO skill (skill_cat_id, skill_name) VALUES (?,?)";
    $skill_cat_id = 1;

    for ($i = 0; $i < count($backend); $i++){
        $skill_name = $_POST["skill_name"];
        if($stmt = $mysqli->prepare($sql2)){
        $stmt->bind_param("is", $skill_cat_id, $backend[$i]);
        if ($stmt->execute()) {

            echo "<script>
            alert('Success!'); 
            </script>";
        }
        else{
            echo "<script>
            alert('Failure!');

            </script>";
        }
        }
    }
}

And the HTML for looks like this:

     <h5>Backend Technologies </h5>
            <div class="container">
            <div id = "backendDiv">
            <?php
            $backend=getbackendtech();
            while($row = $backend -> fetch_assoc()) {
            //    echo "<input type='checkbox' value='{$data['skill_name']}'>". $data['skill_name'];
            echo "<div class=\"list-group-item checkbox\" id = \"backendCheckBoxes\">
            <label><input type=\"checkbox\" name=\"backend[]\" class=\"common_selector form\" value='{$row['skill_name']}'>&nbsp;{$row['skill_name']}</label>
            </div>";
            }
            echo"<input type=\"button\" class='btn btn-warning btn-sm' id = \"addBackendButton\" value = \"Add\" onclick=\"addSkill('backendCheckBoxes', 'backendDiv', 'backend', 'addBackendButton')\">";
         ?>
         </div>
        </div>

And here is the addSkill event:

function addSkill(checkBoxDivId, divId, nameId, buttonId){
    //Variables
    //Creating new elements for new skills and
    //setting their attributes
    let count = 0;
    console.log(checkBoxDivId);
    let existingSkills = document.querySelectorAll("div[id =" + checkBoxDivId +"]");

    console.log(existingSkills);
    for (let i = 0; i < existingSkills.length; i++){

        count++;
    }
    let uniqueId = count+1;
    console.log(uniqueId);
    let hiddenValue = document.createElement("input");
    hiddenValue.setAttribute("hidden", true);
    hiddenValue.setAttribute("name", "skill_name");

    let checkBoxDiv = document.createElement("div");
    checkBoxDiv.setAttribute("id", checkBoxDivId);
    checkBoxDiv.setAttribute("class", "list-group-item checkbox");
    //console.log(checkBoxDiv);

    let textBoxParent = document.getElementById(divId);
    //console.log(textBoxParent);
    let newTextBox = document.createElement("input");

    newTextBox.setAttribute("type","text");
    newTextBox.setAttribute("id", "newTextBox");

    let newCheckBox = document.createElement("input");


    newCheckBox.setAttribute("name", nameId);
    newCheckBox.setAttribute("class", "common_selector form");
    newCheckBox.setAttribute("type","checkbox");
    newCheckBox.setAttribute("checked", true);
    newCheckBox.setAttribute("value", uniqueId);


    let newLabel = document.createElement("label");
    newLabel.setAttribute("for", "newCheckBox");

    let addButton = document.getElementById(buttonId);
    //console.log(addButton);

    //adding textbox to page
    textBoxParent.appendChild(newTextBox);




    //When an enter key is pressed the newly created textBox
    //will be removed and a new checkbox will appear
    newTextBox.addEventListener("keypress", function(event) {
      // Number 13 is the "Enter" key on the keyboard
          if (event.keyCode === 13) {

            //console.log(newTextBox.value);
            //Canceling the default action, if needed
            event.preventDefault();
            event.stopPropagation();

            //Setting Label value
            newLabel.innerHTML = newTextBox.value;


            let skill_name = newLabel.innerHTML;
            console.log(newCheckBox.getAttribute("value"));

            //posting skill name to database

            hiddenValue.setAttribute("value", newLabel.innerHTML);
            console.log(hiddenValue);
            //Remove textbox from page
            textBoxParent.removeChild(newTextBox);


            //Adding new Checkbox to Div
            checkBoxDiv.appendChild(newCheckBox);
            checkBoxDiv.appendChild(newLabel);
            //checkBoxDiv.appendChild(hiddenValue);

            //Adding new Checkbox Div to page
            addButton.before(checkBoxDiv);

            $.ajax({
                type: 'post',
                data: {skill_name: skill_name},
                success: function(response){
                    alert(skill_name);
                }

            });

          }

    });

}
  • Do you have [error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) turned on? You should be seeing an "undefined index" notice for this: `$skill_name = $_POST["skill_name"]`. There is no input named `skill_name`. That right there should be `$backend[$i]`. You're iterating your array but never utilizing any values from it. – El_Vanja Mar 20 '20 at 00:26
  • Ok so I might have mixed up some old code with some new code. I used to have a hidden field named skill_name but that would only allow me to post one skill at a time with form submission. Now when I try to insert the $skill_name as $backend[$i] in my for loop, I get a php error Fatal error: Uncaught Error: Only variables can be passed by reference. – kamilah carlisle Mar 20 '20 at 18:16
  • Can you please edit the question with the changed code and specify where exactly does this error appear? – El_Vanja Mar 20 '20 at 19:21
  • I changed the code to insert $backend[$i] as skill_name and I said the error occurs here, when I try to bind the parameter $backend[$i] to the skill_name column. – kamilah carlisle Mar 21 '20 at 20:52

0 Answers0