2016-08-12 150 views
-1

我正在搜索2天的錯誤,但無法找出有什麼問題。我希望有人能幫助我。PHP MYSQL:SQLSTATE [HY093]:無效的參數編號:綁定變量的數量與令牌的數量不匹配

$query = "INSERT INTO Patient (patients_ID, height, nameOfTheFamilyDoctor, 
    nameOfTheHealthInsurance, weight, birthDate, station, room ) VALUES 
    (:patient, :height, :nameOfTheFamilyDoctor, 
    :nameOfTheHealthInsurance, :weight, :birthDate, :station, :room) "; 

    //Again, we need to update our tokens with the actual data: 

    if (ctype_digit($_POST['height']) && ctype_digit($_POST['weight'])) { 

     $query_params = array(

      ':patient' => $_POST['patientsID'], 
      ':height' => $_POST['height'], 
      ':nameOfTheFamilyDoctor' => $_POST['nameOfTheFamilyDoctor'], 
      ':nameOfTheHealthInsurance' => $_POST['nameOfTheHealthInsurance'], 
      ':weight' => $_POST['weight'], 
      ':birthDate' => $_POST['birthDate'], 
      ':station' => $_POST['station'], 
      ':room' => $_POST['room'], 
     ); 
    } 

    //time to run our query, and create the user 
    try { 
     $stmt = $db->prepare($query); 
     $result = $stmt->execute($query_params); 
    } catch (PDOException $ex) { 
     // For testing, you could use a die and message. 
     //die("Failed to run query: " . $ex->getMessage()); 

     //or just use this use this one: 
     $response["success"] = 0; 
     $response["message"] = "Database Error2. Please Try Again!" . $ex->getMessage();; 
     die(json_encode($response)); 
    } 

我收到此錯誤信息:

{ 「成功」:0, 「消息」:「數據庫誤差2,請重試SQLSTATE [HY093]:無效的參數號:號綁定變量不匹配的令牌數量「}`

我已經檢查的所有變量的拼寫錯誤等

感謝所有您的幫助。

+3

當'height'或'weight'不能通過'ctype_digit'驗證時,你肯定會得到這個錯誤。 – Bert

+0

創建$ query_params的條件是不是很奇怪,但執行需要那些參數的查詢不是? –

+0

將你的try/catch放入你的if語句中,否則查詢將嘗試在沒有綁定變量的情況下運行。 – aynber

回答

0

$_POST['height']$_POST['weight']將會是一個字符串。嘗試使用is_numeric而不是ctype_digit。如有必要,您可以通過intval轉換爲整數。

var_dump($query_params)在嘗試/ catch塊之前...看看它是否存在於您的if()聲明之外。你會看到它是空的。

最後,你需要重新思考你的邏輯......如果你的if()聲明失敗會發生什麼?繼續查詢有意義嗎?在這種情況下,您的try/catch應該在if()聲明中......然後,您應該創建一個else來處理錯誤。 (或者,你可以拋出一個錯誤,並在其他地方有一個錯誤處理程序)。

相關問題