如果表单字段为null,是否可以告诉php不要发布数据?
现在,我在insert.php页面中的post变量如下所示:
fname = $_POST['firstname'];
lname = $_post['lasname'];
sql = "UPDATE profile SET first='.$fname.', last='.$lname.' WHERE id='.$id.'";
如果我的表单字段为空或空,我希望$fname $lname不要发布。做这件事最好的方法是什么?
当前,当我提交更新时,如果这些字段是空的,则如果没有插入空行,则使用空行更新整个表。
发布于 2013-10-04 14:36:54
您可以在每个字段中使用这样的内容:
$fname = empty($_POST['firstname']) ? null : $_POST['firstname'];
如果表单字段不存在或输入为空,这将将$fname
设置为空。否则,它将使用原始值。
更新
如果只想更新非空字段,则需要添加一些额外的逻辑:
if($fname !== null && $lname !== null) {
// update both
}
else if($fname !== null) {
// update just fname
}
else if($lname !== null) {
// update just lname
}
发布于 2013-10-04 14:45:35
Is it possible to tell php to NOT post data if the form field is null?
--不是PHP发布的数据,而是您点击表单提交按钮时的浏览器。为了防止在字段为空时发生这种情况,您必须使用客户端(javascript),它首先验证是否确实在表单提交之前填写了字段。
我就是这么理解你的问题的。如果不希望在$_POST
变量为空时创建SQL查询,则只需使用If条件或三元运算符即可。
发布于 2013-10-04 14:47:22
我会这么做:
$fname = isset($_POST['firstname']) && strlen($_POST['firstname']) > 0 ? $_POST['firstname'] : null;
这样,如果设置变量而不是空变量,$fname将被定义为$_POST‘$fname’值,否则它将是null
。
顺便说一句,如果您在双引号("
)中工作,则不需要使用点来向$sql字符串添加值。更重要的是,您的语法是错误的。这是一种工作方式:
$sql = "UPDATE profile SET first='$fname', last='$lname' WHERE id='$id'";
您应该而不是使用这种SQL查询生成。它容易受到SQL注入的影响。最好使用、PDO、或MySQLi参数化查询。
顺便说一句,如果您想要在值为空的情况下拒绝插入,最好在创建MySQL表时(将一个not null
属性分配给该列)。例如:
CREATE TABLE user(
first VARCHAR(50) NOT NULL,
last VARCHAR(50) NOT NULL
)
**编辑:如果我理解得很好,这就是你想要的:
$valuesToAdd = "";
// Concatenate values to the query if they are defined
if (isset($_POST['firstname']) && strlen($_POST['firstname']) > 0) $valuesToAdd .= "first = '{$_POST['firstname']}',";
if (isset($_POST['lastname']) && strlen($_POST['lastname']) > 0) $valuesToAdd .= "last = '{$_POST['lastname']}',";
// Repeat for any other values...
// By default, the SQL string is empty
$sql = "";
// If changes were made...
if (strlen($valuesToAdd) > 0) {
// Remove the last ","
$valuesToAdd = substr($valuesToAdd, 0, strlen($valuesToAdd)-1);
// Generate the SQL string with the values which will be added
$sql = "UPDATE profile SET {$valuesToAdd} WHERE id='{$id}'";
// echo $sql; die;
}
// Check if the SQL string is not empty
if (strlen($sql) > 0) {
// Here the SQL has been generated, use it for a SQL query...
// $con = mysql_connect(...); .....
}
https://stackoverflow.com/questions/19191815
复制