How do I insert multiple checkbox values into a table?

前端 未结 4 1939
太阳男子
太阳男子 2020-11-29 04:01

I cant seem to find or figure out a working solution to insert multiple checkbox values from a form into a table. The closes I have come is inserting the value of merely one

相关标签:
4条回答
  • 2020-11-29 04:06

    I think you should $_POST[][], i tried it and it work :)), tks

    0 讨论(0)
  • 2020-11-29 04:12

    You need to declare the array in the HTML via

    <input type="checkbox" name="Days[]" value="Daily">
    

    Also you can insert multiple items with one query like this

    $query = "INSERT INTO example (orange) VALUES ";
    for ($i=0; $i<count($checkBox); $i++)
        $query .= "('" . $checkBox[$i] . "'),";
    $query = rtrim($query,',');
    mysql_query($query) or die (mysql_error() );
    

    Also keep in mind that mysql_* functions are officially deprecated and hence should not be used in new code. You can use PDO or MySQLi instead. See this answer on SO for more information.

    0 讨论(0)
  • 2020-11-29 04:19

    I think this should work .. :)

    <input type="checkbox" name="Days[]" value="Daily">Daily<br>
    <input type="checkbox" name="Days[]" value="Sunday">Sunday<br>
    
    0 讨论(0)
  • 2020-11-29 04:32

    You should specify

    <input type="checkbox" name="Days[]" value="Daily">Daily<br>
    

    as array.

    Add [] to all names Days and work at php with this like an array.

    After it, you can INSERT values at different columns at db, or use implode and save values into one column.


    Didn't tested it, but you can try like this. Don't forget to replace mysql with mysqli.

    <html>
    <body>
    <form method="post" action="chk123.php">
    Flights on: <br/>
    <input type="checkbox" name="Days[]" value="Daily">Daily<br>
    <input type="checkbox" name="Days[]" value="Sunday">Sunday<br>
    <input type="checkbox" name="Days[]" value="Monday">Monday<br>
    <input type="checkbox" name="Days[]" value="Tuesday">Tuesday <br>
    <input type="checkbox" name="Days[]" value="Wednesday">Wednesday<br>
    <input type="checkbox" name="Days[]" value="Thursday">Thursday <br>
    <input type="checkbox" name="Days[]" value="Friday">Friday<br>
    <input type="checkbox" name="Days[]" value="Saturday">Saturday <br>
    <input type="submit" name="submit" value="submit">
    </form>
    </body>
    </html>
    

    <?php
    
    // Make a MySQL Connection
    mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("test") or die(mysql_error());
    
    $checkBox = implode(',', $_POST['Days']);
    
    if(isset($_POST['submit']))
    {       
        $query="INSERT INTO example (orange) VALUES ('" . $checkBox . "')";     
    
        mysql_query($query) or die (mysql_error() );
    
        echo "Complete";
    
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题