当某些表单字段为空时,如何提交表单并保存到数据库

时间:2014-04-28 03:55:54

标签: php sql mysqli

我希望我的某些字段留空,对于某些建议但如果某些输入为空,则表单不会提交到数据库。

如果表单字段中包含所有值,则表单工作正常但如果有一个或两个值空白,则所有信息都不会提交到数据库。

<?php
     if(isset($_POST['submit'])){
     //process the form


     $name = $_POST["name"];
     $address = $_POST["address"];
     $contact = $_POST["contact"];
     $transaction = $_POST["transaction"];
     $status = $_POST["status"];
     $flemingia = $_POST["flemingia"];
     $indigofera = $_POST["indigofera"];
     $ipil_ipil = $_POST["ipil_ipil"];
     $acid_ipil_ipil = $_POST["acid_ipil_ipil"];
     $red_calliandra = $_POST["red_calliandra"];
     $white_calliandra = $_POST["white_calliandra"];
     $centrosema = $_POST["centrosema"];
     $goat_manual = $_POST["goat_manual"];
     $lbc_tracking = $_POST["lbc_tracking"];
     $debit_amount = $_POST["debit_amount"];
     $credit_amount = $_POST["credit_amount"];



     $query  = "INSERT INTO orders (";
     $query .= "name, address, contact, transaction, flemingia, indigofera, ipil_ipil, acid_ipil_ipil, ";
     $query .= "red_calliandra, white_calliandra, centrosema, goat_manual, lbc_tracking, debit_amount, credit_amount, status";
     $query .= ") VALUES (";
     $query .= "'{$name}', '{$address}', {$contact}, '{$transaction}', {$flemingia}, {$indigofera}, {$ipil_ipil}, {$acid_ipil_ipil}, ";
     $query .= "{$red_calliandra}, {$white_calliandra}, {$centrosema}, {$goat_manual}, {$lbc_tracking}, {$debit_amount}, {$credit_amount}, {$status}";
     $query .= ")";
     $order_set = mysqli_query($connection, $query);

     if($order_set){
       redirect_to("orders.php");
     } else{
       $message = "order creation failed";
     }

     } else {


     }

1 个答案:

答案 0 :(得分:0)

对于您的每个$_POST vars,

$name = (isset( $_POST['name'] )) ? $_POST['name'] : '';

如果$ name不存在,这将把$ name设置为空字符串。