2014-02-17 85 views
0

我試圖做一個窗體,將檢查是否在數據庫中存在數據庫之前,它會將值插入到數據庫中的密鑰。但是,我似乎無法讓用戶警告已有重複條目。我該如何去做呢?插入前檢查數據庫中的重複條目

表:

<?php require_once("includes/session.php"); ?> 
<?php require_once("includes/db_connection.php"); ?> 
<?php require_once("includes/functions.php"); ?> 
<?php require_once("includes/validation_function.php"); ?> 
<?php find_selected_page(); ?> 
<?php 
if (isset($_POST['submit'])) { 
// Process the form 

//validations 
    $required_fields = array("first_name", "last_name", "nric", "address", "birthdate", "phone", "doctor"); 
validate_presences($required_fields); 

$fields_with_max_lengths = array("phone" => 8); 
validate_max_lengths($fields_with_max_lengths); 

    if(verify_nric($_POST['nric'])) { 
     $errors[] = 'This NRIC exists already.'; 
    } 


    if(!isValid('phone', $_POST['phone'])) { 
     $errors[] = 'Please enter a valid phone number';  
    } 


     if(!isValid('nric', $_POST['nric'])) { 
     $errors[] = 'Please enter a valid nric number';  
    } 




    if (empty($errors)) { 
     // perform Create 


    $name = mysql_prep($_POST["name"]); 
    $age = (int) $_POST["age"]; 
    $nric = mysql_prep($_POST["nric"]); 
    $birthdate = mysql_prep($_POST["birthdate"]); 
    $allergy = mysql_prep($_POST["medical_allergy"]); 
    $history = mysql_prep($_POST["medical_history"]); 
    $phone = (int)$_POST["phone"]; 
    $address = mysql_prep($_POST["address"]); 
    $doctor = mysql_prep($_POST["doctor"]); 

    //escape content 


     // 2. Perform database query 

    $query = "INSERT INTO patients ("; 
    $query .= " name, age, nric, birthdate, medical_allergies, medical_history, 
    phone, address, doctor_assigned"; 
    $query .= ") VALUES ("; 
    $query .= " '{$name}', {$age}, '{$nric}', '{$birthdate}', 
    '{$allergy}', '{$history}', {$phone}, '{$address}', '{$doctor}'"; 
    $query .= ")"; 

    $result = mysqli_query($connection, $query); 

    if ($result) { 
     // Success 
     $_SESSION["message"] = "Record Created."; 


    }else { 
     // Failure 
     $_SESSION["message"] = "Record creation failed."; 
    } 
    } 
} else { 
    // This is probably a GET request 

} // End: If(isset($_POST['submit'])) 

?> 
<?php $layout_context = "admin"; ?> 
<link rel="stylesheet" type="text/css" href="css/dashboard-icons.css" /> 
<link rel="stylesheet" type="text/css" href="css/dashboard-component.css" /> 

<?php echo message(); ?> 
<?php echo form_errors($errors); ?> 

<h2>Create Patient</h2> 

<form action="create_patient.php" method="post"> 
<p>First Name: 
<input type="text" name="first_name" value="" /> 
</p> 

<p>Last Name: 
<input type="text" name="last_name" value="" /> 
</p> 

<p> NRIC/ Foreign ID/ Passport: 
<input type="text" name="nric" value="" /> 
</p> 

<p>Date Of Birth:<br /> 
<input type="text" name="birthdate" value="" /> 
</p> 

<p>Contact Number: 
<input type="text" name="phone" value="" /> 
</p> 

<p>Address: 
<textarea name="address" rows="1" cols="40" align="right"></textarea> 
</p> 

<p>Dentist Assigned:<br /> 
<input type="text" name="doctor" value="" /> 
</p> 

<div id="limit"> 
<p>Medical Allergies:<br /> 
<textarea name="medical_allergy" rows="15" cols="40"></textarea> 
</div> 

<p>Medical History:<br /> 
<textarea name="medical_history" rows="15" cols="40"></textarea> 



<input type="submit" name="submit" value="submit" /> 
</form> 

<br /> 
<a href="manage_content.php">Cancel</a> 
</div> 

驗證功能:

function verify_nric($nric){ 
     global $connection; 

     $query = "SELECT nric "; 
     $query .= "FROM patients "; 
     $query .= "ORDER BY nric ASC"; 
     $nric_set = mysqli_query($connection, $query); 
     confirm_query($nric_set); 
     if ($nric == $nric_set) { 
     return $nric_set; 
     } 
} 

function isValid($what, $data) { 

    switch($what) { 

     // validate a phone number  
     case 'phone': 
      $pattern = "/^[0-9-+()\s]+$/"; 
     break; 


     case 'nric': 
     $pattern = "/^(A-Z)?[0-9]{7}[A-Z]$/i"; 
     break; 

     default: 
      return false; 
     break; 

    } 

    return preg_match($pattern, $data) ? true : false; 

} 

confirm_query

function confirm_query($result_set) { 
    if (!$result_set) { 
     die("Database query failed: ". 
    mysqli_connect_error() . 
    " (" . mysqli_connect_errno(). ")" 
    ); 
} 
    } 
+0

使用SELECT查詢語句來檢查記錄存在或不與給定的值插入之前 –

+0

爲什麼你不嘗試嵌套查詢..就像插入到tableName不存在(選擇...從表) – 2014-02-17 04:58:38

+0

可能的重複-http://stackoverflow.com/questions/20048028 /不檢查-IF-用戶是被採用/ 20048087#2 0048087 –

回答

2

不知道什麼confirm_query()做,但你可以改變你的功能:

function verify_nric($nric){ 
    global $connection; 

    $query = "SELECT nric "; 
    $query .= "FROM patients "; 
    $query .= "WHERE nric='".mysqli_real_escape_string($connection,$nric)."'"; //changed your query a little here 
    $nric_set = mysqli_query($connection, $query); 
    confirm_query($nric_set); // you haven't mentioned what this function does so I'm going to leave it that way. 
    $nric_found=false;      //Added 
    if(mysqli_num_rows($nric_set)>0){   // 
    $nric_found=true;       //These 
    }           // 
    return $nric_found;      //Lines 
} 


我們解釋一下你在哪裏錯了:

  1. 你的選擇查詢返回的所有身份證,但你並沒有獲取的 值和檢查,對$nric。您需要使用 mysqli_fetch_array()從結果集 $nric_set

  2. $nric == $nric_set無效獲取值,因爲你是 一個結果($nric_set)與值進行比較$nric
+0

而downvote的原因是? –

+1

如果知道原因那會很好。不是嗎?無條件降低投票已經成爲近期SO'的一種趨勢。我懷疑downvote的原因是因爲使用了**全局**關鍵字。 –

+0

謝謝你的幫助,我投票支持你=)。我現在全部工作了謝謝! =) – user3098046