【问题标题】:Error when checkbox not checked in php mysql form [duplicate]未在 php mysql 表单中选中复选框时出错 [重复]
【发布时间】:2017-06-27 22:22:15
【问题描述】:

我的表单中的复选框在选中时可以输入一个真值 (1),否则,该列的值为假 (0)。但是,当我在未选中复选框的情况下运行表单时,它给了我这个错误 -

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

这里是用于创建产品的 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>

【问题讨论】:

  • 第 37 行是什么?
  • 请不要将 sn-ps 用于此类内容。它也无法显示正确的语法突出显示。

标签: javascript php mysql checkbox


【解决方案1】:

在这里,您在尝试使用它之前检查该值是否存在:

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

【讨论】:

  • 成功了!非常感谢。
  • 如何在更新产品页面中实现这一点?
猜你喜欢
  • 2017-11-12
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多