ilarsona
ilarsona

Reputation: 436

How to access checkboxes with unknown names in PHP

I have a MySQL database with auto-increment column "line numbers." In the form that is being submitted to the script, there are check boxes. I don't know how many check boxes there are, because each Customer has a different number of services that they're allowed to access. When the check box is clicked, they've used a service and the integer in column Available for that row needs to decrease by one. Sometimes, the user can say that multiple services were used and more than one row needs to be affected.

Where I'm becoming stuck is on two things: how the check boxes are named, and if I name them by the line number, how to access them with PHP.

while($cell = mysqli_fetch_array($service_details_query)) {
                    echo "</br>";
                    echo "<input type='checkbox' name='" . $cell['line_item'] . "'>";
                }

The above code is how I'm making the check box. Probably the biggest part of the question is how I could better name it so that I can predict what names to look for ($_POST[name]) when the form is submitted (instead of a random number).

The other part I'm getting stuck on is, if I do decide to keep the naming strategy, how to fetch it. What I've thought of is to use a loop to extract the true/false data that's carried, but I don't know how to execute that. Sure, I can write a for or while loop, but I don't know how to extract the name of the object.

I'm sort of a beginner when it comes to PHP. I know how to get my way around with for loops, while loops, basic commands such as echo... but I'm really lacking

Upvotes: 2

Views: 237

Answers (4)

I would prefix the names depending on context, for example:

<input type='checkbox' name='service_" . $cell['line_item'] . "'>"

This way, if the checkbox represents a service, you could identify it by the prefix.

Upvotes: 0

icecub
icecub

Reputation: 8773

Alright. Since you wanted to be able to add extra data, I thought I'd start over complicating stuff a lot! But it does the job. Explanation can be found in the codes comments.

First the HTML and Javascript part:

<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript">
        // First we need to get our form
        var myForm = document.getElementById("myForm");

        // Next we're adding an event listener to the form submit so we can catch it
        // and use a function to do some stuff before sending it over to the php file
        myForm.addEventListener("submit", function(event){
            // Now we need to temporarely stop the form from submitting
            event.preventDefault();

            // Next we need to get all our checkboxes
            var checkBoxes = document.getElementsByClassName("myCheckbox");

            // Now we need some arrays for all the data we're going to send over
            // Basicly you make one for each data attribute
            var lineNr = [];
            var someThing = [];

            // Lets loop through all checkboxes
            for (var i=0; i<checkBoxes.length; i++) {
                // Catch the ones checked
                if (checkBoxes[i].checked) {
                    // Push the data attribute values to the arrays
                    lineNr.push(checkBoxes[i].dataset.linenr);
                    someThing.push(checkBoxes[i].dataset.something);
                }
            }

            // Now we to JSON encode these arrays to send them over to PHP
            var jsonLineNr = JSON.stringify(lineNr);
            var jsonSomeThing = JSON.stringify(someThing);

            // Since we cannot directly add these variables to our form submit,
            // unless we use Ajax, we need to add them to our form in some
            // hidden fields
            myForm.innerHTML += "<input type='hidden' name='jsonLineNrs' value='"+ jsonLineNr +"' />";
            myForm.innerHTML += "<input type='hidden' name='jsonSomeThings' value='"+ jsonSomeThing +"' />";

            // All done, now we submit our form
            myForm.submit();
        }
        </script>
    </head>
    <body>
        <form method="POST" action="your_php_file.php" id="myForm" accept-charset="utf-8">
            <input type="checkbox" class="myCheckbox" data-linenr="1" data-something="value1" />
            <br />
            <input type="checkbox" class="myCheckbox" data-linenr="2" data-something="value2" />
            <br />
            <input type="checkbox" class="myCheckbox" data-linenr="3" data-something="value3" />
            <br />
            <input type="submit" value="Submit" />
        </form>
    </body>
</form>

Next the PHP part:

<?php

// First we need to decode the JSON strings so we can use them

$jsonLineNrs = json_decode($_POST['jsonLineNrs']);
$jsonSomeThings = json_decode($_POST['jsonSomeThings']);

// Now both of those variables are arrays that contain all the data you wanted
// You can loop each of them to do stuff like
foreach($jsonLineNrs as $jsonLineNr){
    echo $jsonLineNr; //Will echo out each line number
}

// Or if you want to loop through both simultaneously so you can
// keep each checked box data values together:
for($i=0; $i<count($jsonLineNrs)-1; $i++) {
    echo $jsonLineNrs[$i].' - '.$jsonSomeThings[$i];
}

?>

Now before I finish this answer, one last warning: I didn't sanitize the user input in the Javascript part. It would make this answer even a lot more complicated and way to long. Be sure to do this, as you can NEVER EVER trust user input! Even if it's only checkboxes, POST data can be changed before it's submitted!

Upvotes: 0

Elias Nicolas
Elias Nicolas

Reputation: 775

while($cell = mysqli_fetch_array($service_details_query)) {
                    echo "</br>";
                    echo "<input type='checkbox' name='checkboxname[]' value ='".$cell['line_item']."'>";
                }

It should do a $_POST array with the name checkboxname inside that array, you find the values. You can find it threating $_POST['checkboxname'] as an array.

Upvotes: 3

Marcus Abrah&#227;o
Marcus Abrah&#227;o

Reputation: 696

Try name it like: "checkbox_" . $cell['line_item'] so you can do something like this:

foreach($_POST as $name => $value)
{
   if(substr($name, 9) == "checkbox_"){
       //USE the value
   }
}

or you could name like this:

echo "<input type='checkbox' name='services[]' value='" . $cell['id'] . "'>";

and get it as an array like this: $services = $_POST["services"];

Upvotes: 1

Related Questions