我创建了一个表单供用户填写,并在提交时对其进行处理并完成工作。通常只是数据库查询。
对于我正在使用的数据库,某些字段可以为 NULL,因此用户可以在某些字段中留空。然而,在测试这一点时,我尝试将一个或多个字段留空,但表单根本不会真正提交任何内容。当我调试时,当我从 POST 方法检索值时,几乎所有字段的值(甚至是其中包含文本的字段)都变为 NULL。
问题是,我需要能够允许用户提交一些字段为空的表单,因为它们并不是完全必要的。我该怎么办?
我是否必须检查 isset() 中是否有可能为空的所有内容,如果是则将其设置为 NULL?
提前致谢!
编辑:这是表单代码。
<form onsubmit="return confirm('Are you sure you want to save the edits?');" method="post" action="orgedit.php?id=<?php echo $organization_id?>" id="orgform" name="orgform" >
Parent Organization ID: <input type="text" name="parent_id" value="<?php echo $row['parent_id']; ?>"/> <br /><br />
Organization nm: <input type="text" name="org_nm" value="<?php echo $row['org_nm']; ?>"/> <br /><br />
TBR Organization Sysnm: <input type="text" name="tbr_sysnm" value="<?php echo $row['tbr_sysnm']; ?>"/> <br /><br />
Type: <input type="text" name="type" value="<?php echo $row['type']; ?>"/> <br /><br />
Contact nm: <input type="text" name="contact_nm" value="<?php echo $row['contact_nm']; ?>"/> <br /><br />
Financial Info: <input type="text" name="financial_info" value="<?php echo $row['financial_info']; ?>"/> <br /><br />
Other Info: <input type="text" name="other_info" value="<?php echo $row['other_info']; ?>"/> <br /><br />
Active: <input type="text" name="active" value="<?php echo $row['active']; ?>"/> <br /><br />
URL: <input type="text" name="url" value="<?php echo $row['url']; ?>"/> <br /><br />
<input type="submit" value="Save Entry" name="save" />
</form>
这是 php 处理代码:)
if(isset($_GET['id']))
{
$organization_id = $_GET['id'];
$parent_organization_id = $_POST['parent_organization_id'];
$organization_nm = $_POST['organization_nm'];
$tbr_organization_sysnm = $_POST['tbr_organization_sysnm'];
$type = $_POST['type'];
$contact_nm = $_POST['contact_nm'];
$financial_info = $_POST['financial_info'];
$other_info = $_POST['other_info'];
$active = $_POST['active'];
$url = $_POST['url'];
获得值后,我只需转义它们并执行查询。
我已经找到问题所在了!
if(isset($_GET['id']))
{
$organization_id = $_GET['id'];
$parent_organization_id = $_POST['parent_id'];
$organization_nm = $_POST['org_nm'];
$tbr_organization_sysnm = $_POST['tbr_sysnm'];
$type = $_POST['type'];
$contact_nm = $_POST['contact_nm'];
$financial_info = $_POST['financial_info'];
$other_info = $_POST['other_info'];
$active = $_POST['active'];
$url = $_POST['url'];
我从表单中检索了错误的值。这可以通过更改 php 代码或 html 代码来解决。
问题是,一个或多个字段为空的问题仍然存在。如果其中一个字段为空,则不会保存该条目。我检查了日志,它输出的消息是:
PHP Notice: Undefined index: parent_id
PHP Notice: Undefined index: org_nm
PHP Notice: Undefined index: tbr_sysnm
当我没有为任何这些字段编写任何内容并尝试保存表单时,就会发生这种情况。
编辑2:问题再次得到解决。进行了 var 转储,发现当代码尝试检索值时服务器没有给出任何内容。这是一些字段中的拼写错误。
最佳答案
我的第一个猜测是:
您的表单输入可能没有名称属性。仅当输入具有名称属性并且 PHP $_POST
键将是该属性的名称时,才会提交输入数据。
让我们看看OP的代码,看看我的猜测是否正确。
关于php - 如果一个或多个字段为空,HTML 表单不会收集数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12728312/