Monil Shah
Monil Shah

Reputation: 135

PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Below is my code, I am not able to resolve this error. Any help is appreciated. I am trying to update a table in my database.

    public function updateUnit($params){
    $user = 'monil';
    $password = 'Masters123';   
    $dbh = new \PDO('mysql:host=127.0.0.1;dbname=tcsdb', $user, $password);

    $task=array(':UnitCode'=>$params['UnitCode'],':UnitDescription'=>$params['UnitDescription']    ,
      ':UnitName'=>$params['UnitName'], ':UnitID'=>$params['UnitID']);
    echo $params['UnitID'];

    $sth = $dbh->prepare('UPDATE unit SET UnitCode = :UnitCode,'
        . 'UnitDescription = :UnitDescription,UnitName = :UnitName WHERE UnitId=:UnitId');
    $sth->execute($task); 

    return true;
}

Upvotes: 12

Views: 40891

Answers (3)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Parameter names used in execute()/binding should be exact match for the parameter names used in the SQL query. That's the point of named parameters.

You need to check every placeholder in SQL, whether its name matches the name used in execute(), bindParam() or bindValue().

In your case, :UnitID is not the same as :UnitId, there is a difference in the letter case.

In a rare case, the error can be caused by improper placeholder name. The only characters allowed are [a-zA-Z0-9_].

Also, you cannot use the same placeholder more than once, unless the emulation mode is turned on.

Upvotes: 17

smn
smn

Reputation: 11

same errors may occur if you use a "." dot in bindParam

ex.

$query = "select * from t where t1 = :foo.bar";
$stmt = $pdo->prepare($query);
$stmt->execute([':foo.bar' => 'blah']);

Upvotes: 1

Vaibs
Vaibs

Reputation: 2096

The same error arise when you missed : colon while creating statement.

ex: Below statement throws invalid parameter error as password in VALUES is missing : colon.

$stmt = $db->prepare('INSERT INTO members (username,password) VALUES (:username, password)');

Upvotes: 1

Related Questions