mardi 27 juin 2017

Error when checkbox not checked in php mysql form

The checkbox in my form works to put in a true value (1) when the checked and otherwise, the value for the column is false (0).. however, when I run the form without the checkbox checked it gives me this error -

"Notice: Undefined index: publish in C:\xampp\htdocs\phpoop\create_product.php on line 37"

Here is the Product class for creating the product (only including the publish variable)

class Product{

    // database connection and table name
    private $conn;
    private $table_name = "products";

    // object properties
      public $publish;


    public function __construct($db){
        $this->conn = $db;
    }

    // create product
    function create(){

        //write query
        $query = "INSERT INTO
                    " . $this->table_name . "
                SET
                    publish=:publish";

        $stmt = $this->conn->prepare($query);

        // posted values
        $this->publish=htmlspecialchars(strip_tags($this->publish));

        // to get time-stamp for 'created' field
        $this->timestamp = date('Y-m-d H:i:s');
        $this->timestamp2 = date('Y-m-d H:i:s');

        // bind values 
        $stmt->bindParam(":publish", $this->publish);


        if ($stmt->execute()){
            return true;    

        }else{
            return false;
        }

    }

and this is where the form is located for creating the product

// if the form was submitted 
if ($_POST){

    // set product property values
    $product->publish = $_POST['publish'];

    if(isset($_POST['publish'])){
    $published = $_POST['publish'];
    }
    else{
        $published = 0;
    }

    // create the product
    if($product->create()){
        echo "<div class='alert alert-success'>Product was created.</div>";
    }


}

?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
  <input type="checkbox" name="publish"  value="1" class="form-control" <?php if(isset($_POST['publish'])) echo "checked='checked'";?>/>
  <button type="submit" class="btn btn-primary">Create Product</button>
 </form>




Aucun commentaire:

Enregistrer un commentaire