简体   繁体   English

根据用户在PHP中的选择发布表单值

[英]Post form values based on user selection in PHP

I need to make a form where users can insert products in a database. 我需要制作一个表格,用户可以在其中插入产品。 The database has columns "Name", "SKU", "Type", "Attributes". 该数据库具有“名称”,“ SKU”,“类型”,“属性”列。 The form has fields "Name", "SKU", "Price" and a select box "Type" with three options - "Furniture", "Dvd-disc" and "Book". 表单具有“名称”,“ SKU”,“价格”字段和带有三个选项的“类型”选择框-“家具”,“ DVD光盘”和“书籍”。

Additional form fields are show based on what user chooses in the "Type" selection. 根据用户在“类型”选择中选择的内容显示其他表单字段。 For example, if the user chooses "Furniture" from the select box, then three fields, "Height", "Width", "Length", appear. 例如,如果用户从选择框中选择“家具”,则会出现三个字段,“高度”,“宽度”,“长度”。 If he chooses "Books", a "Weight" field appears, and if he chooses "DVD-disc", the field "Size" appears. 如果他选择“书”,则出现“权重”字段,如果他选择“ DVD-光盘”,则出现“大小”字段。

The jQuery funcion to hide/show required fields is not implemented yet, so don't mind that. 隐藏/显示必填字段的jQuery函数尚未实现,所以不要介意。

EDIT: When I post, for example, the type Disc and Size 700, and do "var_dump($_POST);" 编辑:例如,当我发布类型Disc和Size 700并执行“ var_dump($ _ POST);”时 I get: 我得到:

array(8) { ["sku"]=> string(8) "BT944RUR" ["name"]=> string(22) "Third insert from page" ["price"]=> string(5) "56.25" ["type"]=> string(8) "DVD-disc" ["size"]=> string(3) "700" ["dimensions"]=> array(3) { ["height"]=> string(0) "" ["width"]=> string(0) "" ["length"]=> string(0) "" } ["weight"]=> string(0) "" ["submit"]=> string(6) "Submit" }

It collects the Size value from the form but doesn't pass it further. 它从表单收集Size值,但不会进一步传递它。

HTML form: HTML形式:

<form action="" method="post">
    <div class="form-group">
        <label for="sku">SKU</label>
        <input type="text" class="form-control" id="sku" name="sku">
    </div>
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name" name="name">
    </div>
    <div class="form-group">
        <label for="price">Price</label>
        <input type="text" class="form-control" id="price" name="price">
    </div>
    <div class="form-group">
        <label for="type">Disabled select menu</label>
        <select id="type" name="type" class="form-control">
            <option></option>
            <option>DVD-disc</option>
            <option>Book</option>
            <option>Furniture</option>
        </select>
    </div>
    <div class="form-group">
        <label for="size">Size</label>
        <input type="text" class="form-control" id="size" name="size">
    </div>
    <div class="form-group">
        <label for="dimensions[height]">Height</label>
        <input type="text" class="form-control" id="height" name="dimensions[height]">
    </div>
    <div class="form-group">
        <label for="dimensions[width]">Width</label>
        <input type="text" class="form-control" id="width" name="dimensions[width]">
    </div>
    <div class="form-group">
        <label for="dimensions[length]">Length</label>
        <input type="text" class="form-control" id="length" name="dimensions[length]">
    </div>
    <div class="form-group">
        <label for="weight">Weight</label>
        <input type="text" class="form-control" id="weight" name="weight">
    </div>
    <input type="submit" name="submit" id="submit" class="btn btn-default">
</form>

PHP code so far (to pass the variables to the insert): 到目前为止的PHP代码(将变量传递给插入):

if(isset($_POST['submit'])) {
    $sku = $_POST['sku'];
    $name = $_POST['name'];
    $price = $_POST['price'];
    $type = $_POST['type'];
    $attributes = '';

    if(isset($_POST['dimensions']) && !empty($_POST['dimensions'])) {
        $attributes = implode(' x ', $_POST['dimensions']);
    }
    else if(isset($_POST['weight']) && !empty($_POST['weight'])) {
        $attributes = $_POST['weight'];
    }
    else if(isset($_POST['length']) && !empty($_POST['length'])) {
        $attributes = $_POST['length'];
    }

    $fields = [
        'SKU'=>$sku,
        'Name'=>$name,
        'Price'=>$price,
        'Type'=>$type,
        'Attributes'=>$attributes
    ];

    $product = new Products();
    $product->insert($fields);
}

Insert function (in a different file): 插入函数(在另一个文件中):

    public function insert($fields) {

        $implodeColumns = implode(', ', array_keys($fields));
        $implodeValues = implode(", :", array_keys($fields));

        $sql = "INSERT INTO products ($implodeColumns) VALUES (:".$implodeValues.")";

        $result = $this->connect()->prepare($sql);

        foreach ($fields as $key => $value) {
            $result->bindValue(':'.$key, $value);
        }

        $resultExec = $result->execute();

        if($resultExec) {
            header('Location: index.php');
        }
    }

I think the if statements are wrong. 我认为if陈述是错误的。 I can pass the dimensions to the database in such a way but if I try to send size or weight it just passes epmty values with two "x" between them. 我可以通过这种方式将尺寸传递给数据库,但是如果我尝试发送尺寸或重量,它只会传递带有两个“ x”的epmty值。

And additional question: can I achieve this without using conditional statements? 还有一个问题:我可以不使用条件语句来实现这一目标吗? I'm open to different approaches. 我愿意接受不同的方法。

A few notes. 一些注意事项。

Since you're only interested if the user has submitted values, you can simplify your if statements: 由于您仅对用户是否提交了值感兴趣,因此可以简化if语句:

if($_POST['dimensions']) {
    $attributes = implode(' x ', $_POST['dimensions']);
}
else if($_POST['weight']) {
    $attributes = $_POST['weight'];
}
else if($_POST['length']) {
    $attributes = $_POST['length'];
}

I do however wonder why you don't record height/width/length separately in the database? 但是,我不知道为什么您没有在数据库中单独记录高度/宽度/长度?

If I were you, I would update my database table to reflect what you're collecting from your users (or vice versa), and do a straight insert of all columns every time a user submits a form, even if some of the fields values have been submitted empty. 如果您是我,我将更新数据库表以反映您从用户那里收集的信息(反之亦然),并且每次用户提交表单时都会直接插入所有列,即使某些字段值已被提交为空。 This has the added bonus of simplifying your life later on if/when you decide to add or remove columns in the database or front-end form. 如果您决定在数据库或前端表单中添加或删除列,那么这还有一个额外的好处,那就是简化了以后的工作。

And finally, please, please either clean the user input, or use prepared SQL statements to avoid SQL injection attacks . 最后,请清除用户输入或使用准备好的SQL语句以避免SQL注入攻击

The problem is your first if : 问题是你的第一个if

if(isset($_POST['dimensions']) && !empty($_POST['dimensions'])) {

As seen in your HTML, dimension is an array of inputs: length, height, width. 如HTML所示,维度是输入数组:长度,高度,宽度。 This means the variable will never be empty. 这意味着该变量永远不会为空。

$dimensions = [
    'length' => '',
    'width'  => '',
    'heigth' => '',
];

echo empty($dimensions) ? 'dimensions is empty': 'dimensions is not empty'; //output: dimensions is not empty

As solution would to "clean" out nullable values from your array before testing if its empty. 解决方案是在测试数组是否为空之前从数组中“清除”可空值。 To do this, you can resort to array_filter 为此,您可以求助于array_filter

echo empty(array_filter($dimensions)) ? 'dimensions is empty': 'dimensions is not empty'; //output: dimensions is empty

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM