简体   繁体   中英

Insert value checkbox in database. Unchecked=0 checked=1

I'm trying to get a value of a checkbox in the database. If the box is checked, the value is 1 If the box is unchecked, the value is 0.

In my index page my table looks like:

<td style="width: 100px" class="auto-style1"><input type="checkbox" name="ele3" id="rallydag" 
value="1"></td>

And in my page, what will put it in my database, i have:

$ele3 = mysqli_real_escape_string($link, $_REQUEST['ele3']);

So i have for every day in the week a different checkbox, people can tell us if they can come that day.

Now every post in my database returns at "1". What do i wrong? I searched a lot, but all doesn't work.

If you must use a checkbox then

<form action="action.php" method="post">
<input type="checkbox" name="ele3" value="1" id="rallydag">
<input type="submit" name="save" value="Save to database">
</form>

then in your action.php

$checkbox_value = !empty($_POST['ele3'])?$_POST['ele3']:0;//if value is empty, set to zero, checkbox not checked
//code to insert to database here

And by the way...avoid using mysqli_connect().. just adopt PDO::

Try like Below Code:

<?php 
if(isset($_POST['get_checkbox_value'])){
    $ele3[] = $_POST['ele3'];
    $count = count($ele3);
    for($i = 0; $i < $count; $i++){
        if($ele3[$i] == "" && empty($ele3[$i])){
            echo "<script>alert('0')</script>";
        }else{
            echo "<script>alert('1')</script>";
        }
    }
}
?>
<form method="post">
   <table>
        <tr><td style="width: 100px" class="auto-style1"><input type="checkbox" name="ele3[]" id="rallydag"> Day</td></tr>
        <tr><td><input type="submit" name="get_checkbox_value" value="submit"></td></tr>
   </table>
</form>

Check input set with isset function.

$ele3 = isset($_POST['ele3']) ? $_POST['ele3'] : 0;

HTML: You don't need to give value for the check box

<td style="width: 100px" class="auto-style1"><input type="checkbox" name="ele3" id="rallydag"></td>

in php:

$CheckBoxValue = 0;
if(isset($_POST['ele3'])) $CheckBoxValue = 1; // well be true if the checkbox is checked
//your insert code using $CheckBoxValue

HTML Code:

<input type="checkbox" name="ele3" id="rallydag" onclick="setValue(event)">

JS Code:

function setValue(event){
    if($(event.currentTarget).is(":checked")){
       $(event.currentTarget).val('1')
    }else{
           $(event.currentTarget).val('0')
    }
}

PHP Code:

$ele3 = $_POST['ele3'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM