Php – inserting values from multipe selected checkboxes into database

checkboxdatabaseformsmysqlphp

So the whole scenario is as follows:

I have a form on my website which has multiple values of checkboxes. For example, "price" has four checkboxes. The user can select anywhere from none to all four checkboxes.

I am unable to insert the "SELECTED" checkbox value into the table of the database. I have tried all the methods that I could find on Google and Stackoverflow.

I am relatively new into PHP, so I know very little about it. But to get this problem right, I have gone through various documentations, many in fact.

Anyways, here is what I am doing right now, and it works. But it's a bad method and I know there would be a much more efficient way of doing that.

<div class="panel-body">
     <label class="checkbox-inline"><input type="checkbox" name="price1" value="Less than 10,000, "> Less than 10,000</label>
     <label class="checkbox-inline"><input type="checkbox" name="price2" value="10,001 to 15000, "> 10,001 - 15000</label>
     <label class="checkbox-inline"><input type="checkbox" name="price3" value="15,001 to 25000, "> 15,001 - 25000 </label>
     <label class="checkbox-inline"><input type="checkbox" name="price4" value="25,001 to 35000, "> 25,001 - 35000 </label>
     <label class="checkbox-inline"><input type="checkbox" name="price5" value="35,001 and more, "> 35,001 and more </label>
</div>

So basically each of the individual checkboxes for the price has its own independent name.

The corresponding PHP is as follows

            <?php
        session_start();

        $_SESSION["f1"]=$_REQUEST["price1"];
        $_SESSION["f2"]=$_REQUEST["price2"];
        $_SESSION["f3"]=$_REQUEST["price3"];
        $_SESSION["f4"]=$_REQUEST["price4"];
        $_SESSION["f5"]=$_REQUEST["price5"];
        $_SESSION["f"]=$_SESSION["f1"].$_SESSION["f2"].$_SESSION["f3"].$_SESSION["f4"].$_SESSION["f5"];


        $z6=$_SESSION["f"];

        require_once('ConnectDB.php');
        $conn=mysql_connect(SERVER,USER,PASSWORD);
        mysql_select_db(DATABASE,$conn);

        query="insert into mobile_frm values('".$z6."')";
        mysql_query($query) or die(mysql_error());


        echo"Thanks for using us";
        header('Location: gadget.html');
        mysql_close($conn);

        ?>

This is the PHP script that writes the form value in the Database. I have only included a part of it to keep it plain and simple.

Here I am just taking all the individual values and making one string out of them.

Please give me some direction into it.

Best Solution

You can send an array of form elements, just change your markup to:

<input type="checkbox" name="prices[]" value="Less than 10,000, ">
<input type="checkbox" name="prices[]" value="10,001 to 15000, "> 
// etc...

Then, PHP side:

$prices = $_POST['prices'];   // this is now an array, work on it
Related Question