2017-11-18 13 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; 
    } 
} 

希望它爲你工作

相關問題