2017-11-18 91 views
0

这是我有,它不工作。我需要检查Your_Location.php中的字段是否为空。如果是,则抛出错误。如果不;按照以下方式运行查询。如果我扔//这将工作,如果(!mysqli_query($康恩,$的SQLInsert))你如何编码PHP来检查空容器,如果没有,然后运行SQL查询?

<?php 
    //session_start(); 
    include 'dbConfig.php'; 
    include 'Your_Location.php'; 

    $childfirst = $_POST['element_1']; 
    $childlast = $_POST['element_2']; 
    $childdobyear = $_POST['element_3_3']; 
    $childdobmon = $_POST['element_3_1']; 
    $childdobday = $_POST['element_3_2']; 
    $childbaptize = $_POST['element_4']; 
    $childrelationship = $_POST['inputrelation']; 
    $childdob = "$childdobyear-$childdobmon-$childdobday"; 



    $sqlinsert="INSERT INTO memchild (ID, FirstName, LastName, DOB, Baptize, Relationship) 
    VALUES 
    ('$getid2','$childfirst','$childlast','$childdob','$childbaptize','$childrelationship')"; 



    //Build arrays of fields 

    $required = array('element_1', 'element_2', 'element_3_3', 'element_3_2', 'element_3_1', 'elelment_4', 'inputrelation'); 

    //Loop to check for empties 
    $error = false; 

    foreach($required as $fields) { 
     if(empty($_POST[$fields])){ 
      $error = true; 
     } 
    } 

    if($error){ 
    Sleep(3) 
    ?> 
    <script> 
     document.getElementById('li_9').innerHTML = '* $childfirst Make sure the fields are not empty.'; 
    </script> 
    <?php 
    exit(); 
    }Else{ 
    mysqli_query($conn,$sqlinsert) 
    ?> 
    <script> 
     document.getElementById('li_9').innerHTML = '$childfirst $childlast has been added.'; 
    </script> 
    <?php 
    sleep(3); 
    echo "<meta http-equiv='refresh' content='0'>"; 
    } 
    ?> 
+0

这可行,但我需要检查,看看字段是空的。 ”; } ?> –

+0

这与'Java'有什么关系?你是否意指'JavaScript',这是一种完全不同的语言? – Andreas

回答

1

第一次尝试,以检查是否实际存在的关键。

$childfirst = isset($_POST['element_1'])? $_POST['element_1'] : null; 

其次,你可以检查哪些字段没有填写:

$errorMessage = ''; 
foreach($required as $key) { 
    if(empty($_POST[$key])){ 
     $error = true; 
     // break; // Uncomment if you want to exit the loop if one field is not set 
     // $errorMessage .= $key . ' is not filled in'; // Uncomment if you want to add message for every missing key 
    } 
} 

你的脚本,你想PHP值与JavaScript结合起来,实际上你需要回声或打印样值此:

<script> 
    document.getElementById('li_9').innerHTML += "* <?php echo $childfirst;?> Make sure the fields are not empty."; 
</script> 

,也为第二个

<script> 
    document.getElementById('li_9').innerHTML += "<?php echo $childFirst . ' ' . $childLast;?> has been added."; 
</script> 
+0

的作品,但它不打破循环,如果我取消注销休息。 –

+0

@JohnHang它将退出循环并继续执行foreach(){}之后的行。如果你想停止执行代码,请替换break;用exit(); –

0

喂你的错误,你传递字符串值,以检查其不为空已经

改变这条线

$required = array('element_1', 'element_2', 'element_3_3', 'element_3_2', 'element_3_1', 'elelment_4', 'inputrelation'); 

$required = array("$element_1", "$element_2"); 

添加其他元素也

并改变这个太

foreach($required as $fields) { 
    if(empty($fields)){ 
     $error = true; 
    } 
} 

希望它为你工作

相关问题