处理从表单输入到sql的空值

xcitsw88  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(348)

所以,
我尝试创建动态sql查询,我们假设:
如果get或post没有变量集,我们称之为变量集 NOT SET 如果设置了\u get或\u post,但值为空,则称之为 EMPTY 如果设置了\u get或\u post,但值不是空的,那么我们称之为 NON-EMPTY 现在我们可以很容易地储存 EMPTY 以及 NON-EMPTY mysql中的变量(因为我们知道最终用户的意图,因为变量已经设置好了)
我们目前的Map:

EMPTY & NON-EMPTY = whatever the value is...

(对于mysql中的date列,因为它不允许空,所以我们在0000-00-00:00:00中输入。我们把这个逻辑用于 INSERTS 以及 UPDATES ```
NOT-SET in PHP = NULL in database? (since we don't know anything about the value)

现在,对于数据不存在的情况(例如insert语句),这种方法非常有效,但是update语句呢?
如果记录已经有值了呢?
我想在update语句中使用not set变量作为被忽略的变量?
因此,如果post[“name”]未设置为 `INSERT` ,则仍将其作为空值插入

INSERT INTO person (name) VALUES (POST["name"]);

但是,如果是 `UPDATE` 声明,我们完全忽略它。

UPDATE person
isNull(POST["name"]) ? SET name = POST["null"]

我的困境是我们要做什么 `INSERTS` 以及 `UPDATES` 当这些变量 `NOT SET` ?
6gpjuf90

6gpjuf901#

<html>
    <body>
        <form method="post">
            <label for="field_1">Field 1</label>
            <br />
            <input type="text" name="field_1">
            <br />
            <br />
            <label for="field_1">Field 2</label>
            <br />
            <input type="text" name="field_2">
            <br />
            <br />
            <label for="field_1">Field 3</label>
            <br />
            <input type="text" name="field_3">
            <br />
            <br />
            <input type="submit" name="submit" value="submit">
        </form>

        <?php

            // BASIC IDEA:

            // (This example assumes all incoming post values are strings,
            //  if you have, for example, integers, you'd need to remove the 
            //  single quotes around the values in the SQL statement)

            // Loop through POST array
            // foreach _POST variable as key => value
            foreach($_POST as $k => $v) {
                // if not null, blank, or "submit"
                if(!is_null($v)&& $v != ''&& $v != 'submit') {
                    if(!isset($strSQL)) {
                        // If this is the first value, start off the sql string w/ UPDATE
                        $strSQL = "UPDATE your_table " ."SET " .$k ." = '" .$v ."'";
                    } else {
                        // For subsequent values, include a comma and space before new value
                        $strSQL = $strSQL ."', SET " .$k ." = '" .$v ."'";
                    }

                }
            }

            // Finish off SQL Command, if one was ever started
            if(isset($strSQL)){
                $strSQL = $strSQL ." WHERE some_field meets_your_conditions;";
                // Run SQL Command (echo just used for example)
                echo $strSQL;
            }

        ?>

    </body>
</html>
x33g5p2x

x33g5p2x2#

如果没有设置:
插入:

INSERT INTO person (name) VALUES (NULL);

更新:
如果没有设置,则不调用update,因为值可以是:
1) null:如果为null,则不需要更新
2) notnull:如果不为null,那么如果将其赋值为null,则会丢失值。
附言:这是我根据对要求的理解提出的建议,但根据实际要求可能会有所不同。

相关问题