在php mysql表单中未选中复选框时出错

时间:2017-06-27 14:18:47

标签: javascript php mysql checkbox

我的表单中的复选框用于在选中时输入真值(1),否则,列的值为false(0)..但是,当我运行表单而未勾选复选框时,它给了我这个错误 -

  

“注意:未定义的索引:在第37行的C:\ xampp \ htdocs \ phpoop \ create_product.php中发布”

以下是用于创建产品的Product类(仅包含发布变量)

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;
        }

    }

这就是表单所在的位置,用于创建产品

// 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>

1 个答案:

答案 0 :(得分:0)

在尝试使用该值之前,您需要检查该值是否存在:

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

但是在这之前(就在它之前)你不是:

$product->publish = $_POST['publish'];

在尝试使用它之前,只需将它包含在相同的逻辑中以检查它是否存在:

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