【问题标题】:How to insert data into db via form and left some form fields empty?如何通过表单将数据插入数据库并将某些表单字段留空?
【发布时间】:2013-08-21 12:54:58
【问题描述】:

我想让用户只插入他们想要插入表格的信息,并且一些表单字段保持空白(如果用户不需要填写)。但是当我尝试通过以下方式在数据库表“目录”中仅插入一些数据时:

if (!empty($_POST['name'])){ $name = $_POST['name'];}
if (!empty($_POST['city'])){ $city = $_POST['city'];}
if (!empty($_POST['country'])){ $country= $_POST['country'];}
if (!empty($_POST['year'])){ $year = $_POST['year'];}

$sql = "INSERT INTO catalog(name,city,country,year)VALUES('$name','$city','$country','$year')";
mysql_query($sql);

它返回错误:undefined variable. 当然,它是同一个变量,它从我留空的 html 表单字段中的内容中获取它的值。

例如,如果我几乎完成了在 db 中插入数据的 html 表单,并且仅将“city”字段留空,则脚本会返回错误,让我知道我的 $city 变量未定义。换句话说,如何使字段为空对于成功插入数据是不必要的?

谢谢!

【问题讨论】:

    标签: php mysql insert-into


    【解决方案1】:

    删除所有if 语句,因此即使变量不包含数据,即使用户没有在该字段中输入任何信息,您也可以定义变量。因此,如果用户没有输入他们的city,该记录仍将插入到catalog 表中,但city 的值为空

    来自

    if (!empty($_POST['name'])){ $name = $_POST['name'];}
    if (!empty($_POST['city'])){ $city = $_POST['city'];}
    if (!empty($_POST['country'])){ $country= $_POST['country'];}
    if (!empty($_POST['year'])){ $year = $_POST['year'];}
    

    $name = $_POST['name'];
    $city = $_POST['city'];
    $country= $_POST['country'];
    $year = $_POST['year'];
    

    【讨论】:

      【解决方案2】:

      试试这个:

      $name = (isset($_POST['name']) && !empty($_POST['name'])) ? $_POST['name'] : '';
      $city = (isset($_POST['city']) && !empty($_POST['city'])) ? $_POST['city'] : '';
      $country = (isset($_POST['country']) && !empty($_POST['country'])) ? $_POST['country'] : '';
      $year = (isset($_POST['year']) && !empty($_POST['year'])) ? $_POST['year'] : '';
      

      【讨论】:

        【解决方案3】:

        改为插入NULL

        将您的代码更改为:

        $name = !empty($_POST['name']) ? $_POST['name'] : NULL;
        $city = !empty($_POST['city']) ? $_POST['city'] : NULL;
        $country = !empty($_POST['country']) ? $_POST['country'] : NULL;
        $year = !empty($_POST['year']) ? $_POST['year'] : NULL;
        

        这样,即使用户没有为某个字段输入任何值,它也会为 NULL 并以NULL 的形式插入到您的数据库中。这将删除 Undefined variable 通知。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-29
          • 2012-12-30
          • 2012-07-03
          • 2022-09-27
          • 2016-06-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多