Home > Mobile >  How to pass checkbox value into database
How to pass checkbox value into database

Time:05-20

What I'm trying to do is to store it's value into database. 

This is my code that is actually not working because it fails at try catch block and shows error (exception $e). It just saves nothing at database. How to fix it?

Index.php: https://pastebin.com/cYDdm9Jz

Process.php

<?php
        if(isset($_POST)){
        $var1 = $_POST['var1'];
        $var2 = $_POST['var2'];
        $var3 = $_POST['var3'];
        $var4 = $_POST['var4'];
        $var5 = $_POST['var5'];
        $var6 = $_POST['var6'];
        $var7 = date("Y-m-d H:i:s");
 
        $sql = "INSERT INTO test2 (var1, var2, var3, var4, var5, var6, var7) VALUES(?, ?, ?, ?, ?, ?, ?)";
        $stmtinsert = $db->prepare($sql);
        try {
 
$result = $stmtinsert->execute([$var1, $var2, $var3, $var4, $var5, $var6, $var7]);
if($result) {
echo 'OK.';
} else {
echo 'Error.';
}
 
} catch (Exception $e) {
echo 'error';
die;
    }
}
?>

CodePudding user response:

<form action="" method="post"  id="check" autocomplete="off">

You did not put action value in your code. You can try putting process.php in your form action value.

CodePudding user response:

Add [] to all names Var6 of your checkbox item in index.php. Like below

<p>
 <input id="field_terms" type="checkbox" required name="var6[]" oninvalid="this.setCustomValidity('agree')" oninput="this.setCustomValidity('')"> do you agree?
</p>
<p>
 <input type="checkbox" id="var5" name="var6[]" value="yes"> do you like it?
</p>
<p>
 <input type="checkbox" id="var6" name="var6[]" value="yes"> are you sure?
</p>

Your process.php will be

if (isset($_POST)) {
        $var1 = $_POST['var1'];
        $var2 = $_POST['var2'];
        $var3 = $_POST['var3'];
        $var4 = $_POST['var4'];
        $var5 = $_POST['var5'];
        $var6 = implode(',', $_POST['var6']);
        $var7 = date("Y-m-d H:i:s");

You can check out this link

  •  Tags:  
  • php
  • Related