Şiyar Yıkmış Şiyar Yıkmış - 1 year ago 86
PHP Question

PHP MYSQL: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I am searching already 2 days for the error but i cant find out what's wrong. I hope that somebody can help me here.

$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();;

I am getting this error message:
{"success":0,"message":"Database Error2. Please Try Again!SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens"}

I have checked all variables for spelling errors, etc.

Thanks for all you help.

Answer Source

$_POST['height'] and $_POST['weight'] is going to be a string. Try using is_numeric instead of ctype_digit. You can convert to an integer via intval if necessary.

var_dump($query_params) before your try/catch block... see if it even exists outside of your if() statement. You will see that it's null.

Lastly, you need to rethink your logic... what happens if your if() statement fails? Does it make sense to continue the query? In that case, your try/catch should be in if() statement... Then, you should create an else to handle errors. (alternatively, you could throw an error and have an error handler elsewhere).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download