简体   繁体   English

通过表单将数据添加到PostgreSQL。 如果变量为null / empty,则添加失败,如何防止这种情况?

[英]Adding data to PostgreSQL via form. Add fails if variable null/empty, how do I prevent this?

I'm adding data to a PostgreSQL database via a PHP form. 我正在通过PHP表单将数据添加到PostgreSQL数据库。 It all feels a bit sketchy. 感觉有点粗略。 My main concern is that; 我主要担心的是; in the event of a variable being null/empty the add fails. 如果变量为null / empty,则添加失败。 How do I prevent this? 我该如何预防?

The simplified code is like this: 简化的代码是这样的:

$name = $_POST['name'];
$movie = $_POST['movie'];
$query = "INSERT INTO data.base(name, movie) VALUES('" . $name . "', '" . $movie . "')";
$result = pg_query($query);
if ( $result ) {
    echo 'Thanks';
} else {
    echo 'Error';
}

So if the $movie variable is null/empty the whole add fails. 因此,如果$movie变量为null / empty,则整个添加操作将失败。

I could do something like this I suppose: 我可以做这样的事情:

$name = $_POST['name'];
if ( ! $name ) {
    $name = '0';
}

But I'd rather keep the cell empty as opposed to inserting false data. 但是我宁愿保持单元为空,而不是插入错误数据。

Any help would be much appreciated. 任何帮助将非常感激。

PHP 7+ is required for my solution. 我的解决方案需要PHP 7+

If your name and movie column can be null, and devault value is null you can do something like this: 如果您的namemovie列可以为空,并且devault值为null ,则可以执行以下操作:

$name = $_POST['name'] ?? null;
$movie = $_POST['movie'] ?? null;
$query = "INSERT INTO data.base(name, movie) VALUES('" . $name . "', '" . $movie . "')";
$result = pg_query($query);
if ( $result ) {
    echo 'Thanks';
} else {
    echo 'Error';
}

unfortunatelly it will be an empty row in you table. 不幸的是,它将在您的表中为空行。

But if you don't want junk rows, do something like this: 但是,如果您不希望出现垃圾行,请执行以下操作:

$name = $_POST['name'] ?? false;
$movie = $_POST['movie'] ?? false;

if ( $name and $movie ) {
    $query = "INSERT INTO data.base(name, movie) VALUES('" . $name . "', '" . $movie . "')";
    $result = pg_query($query);
    echo 'Thanks';
} else {
    echo 'Error';
}

I recommend you to escaping the inputs. 我建议您转义输入。

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

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