2016-08-12 69 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来处理错误。 (或者,你可以抛出一个错误,并在其他地方有一个错误处理程序)。

相关问题