0

This is the form:

            <form action="insert-product.php" method="POST">
                <p>Product Title</p>
                <input type="text" id="title" placeholder="Product title" name="p-title">
                <p>Feature 1</p>
                <input type="checkbox" id="feature-1" name="p-f1">
                <p>Feature 2</p>
                <input type="checkbox" id="feature-2" name="p-f2">
                <p>Feature 3</p>
                <input type="checkbox" id="feature-3" name="p-f3">
                <input type="submit" value="Submit" id="submit">
            </form>

This is the php code:

    <?php
        if(!empty($_POST) and $_POST['p-title']){
            require 'connection.php';

            $title = $_POST['p-title'];
            $f1 = $_POST['p-f1'];
            $f2 = $_POST['p-f2'];
            $f3 = $_POST['p-f3'];

            $prep = $db->prepare('INSERT into products(title, feature1, feature2, feature3) values(?, ?, ?, ?)');
            if ($prep->execute([$title, $f1, $f2, $f3]))
                echo "<h1 class=\"text-success\"> İşlem başarılı. Anasayfaya yönlendiriliyorsunuz. </h1>";
            else
                echo "<h1 class=\"text-danger\"> İşlem başarısız. </h1>";
        }
    ?>

This is the result of when I check all the checkboxes: enter image description here

And this is the result of when I do "not" check all the checkboxes: enter image description here

I need it to be 0 when I do not check, and 1 when I do check. What is the solution for this situation?

Dharman
  • 30,962
  • 25
  • 85
  • 135
burak
  • 109
  • 2
  • 8
  • $f1 = $_POST['p-f1'] ?? 0; – oLDo Jul 20 '22 at 08:56
  • 2
    `$f1 = $_POST['p-f1'];` assumes that `$_POST['p-f1']` is always set, you need to check if it actually is set and react accordingly. Unchecked checkboxes are _not_ submitted – brombeer Jul 20 '22 at 09:04
  • 1
    And you didn't give the checkboxes any value, so even when they are submitted, you just end up with a false-y value. Consider substituting in the 1 to insert into the database, in the case when they are checked – ADyson Jul 20 '22 at 09:06
  • Thanks y'all. `$_POST['p-f1'] ?? 0` did not work, I don't know why. I tried this : `$f1 = !empty($_POST['p-f1']);` and it's all good now. – burak Jul 20 '22 at 09:14

0 Answers0