45

I've been using Yii's active record pattern for a while. Now, my project needs to access a different database for one small transaction. I thought the Yii's DAO would be good for this. However, I'm getting a cryptic error.

CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Here is my code:

public function actionConfirmation
{
    $model_person = new TempPerson();

    $model = $model_person->find('alias=:alias',array(':alias'=>$_GET['alias']));
    $connection=Yii::app()->db2;
            $sql = "INSERT INTO users (username, password, ssn, surname
                    , firstname, email, city, country) 
                    VALUES(:alias, :password, :ssn, :surname
                    , :firstname, :email, :city, :country)";
            $command=$connection->createCommand($sql);
            $command->bindValue(":username", $model->alias);
            $command->bindValue(":password", substr($model->ssn, -4,4));
            $command->bindValue(":ssn", $model->ssn);
            $command->bindValue(":surname", $model->lastName);
            $command->bindValue(":firstname", $model->firstName);
            $command->bindValue(":email", $model->email);
            $command->bindValue(":city", $model->placeOfBirth);
            $command->bindValue(":country", $model->placeOfBirth);
            $command->execute();
            $this->render('confirmation',array('model'=>$model));
}

This constructs the following query (as seen on the application log):

INSERT INTO users (username, password, ssn, surname, firstname, email
                   , city, country) 
VALUES(:alias, :password, :ssn, :surname, :firstname, :email, :city, :country);

FYI $model->placeOfBirth is supposed to be in both city and county values. That's not a typo (just a silly thing I have to do).

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
k to the z
  • 3,217
  • 2
  • 27
  • 41

4 Answers4

105

Just to provide an answer - because this error is pretty common - here are a few causes:

  1. The :parameter name does not match the bind by mistake (typo?). This is what happened here. They have :alias in the SQL statement, but bound :username. So when the param binding was attempted, Yii/PDO could not find :username in the sql statement, meaning it was "one parameter short" and threw an error.

  2. Completely forgetting to add the bindValue() for a parameter. This is easier to do in Yii other constructs like $critera, where you have an array or params ($criteria->params = array(':bind1'=>'test', ':bind2'=>'test)).

  3. another possible reason is invalid character in the placeholder name

  4. Weird conflicts with CDataProvider Pagination and/or Sorting when using together and joins. There is no specific, easy way to characterize this, but when using complex queries in CDataProviders I have had weird issues with parameters getting dropped and this error occurring.

One very helpful way to troubleshoot these issues in Yii is to enable parameter logging in your config file. Add this to your db array in your config file:

'enableParamLogging'=>true,

And make sure the CWebLogRoute route is set up in your log section. This will print out the query that gave and error, and all of the parameters it was attempting to bind. Super helpful!

thaddeusmt
  • 15,410
  • 9
  • 67
  • 67
  • 5
    Good post. I found in my instance that I had a space after one of the col names and that was enough to throw the error. – salonMonsters Dec 19 '11 at 23:52
  • 1
    A list of valid placeholders characters here http://stackoverflow.com/questions/5809951/pdo-valid-characters-for-placeholders – chocolata Jul 08 '13 at 12:04
  • Mine was also a space after one of the column names in the bind call, man that was tough to spot – Wesley Smith Aug 01 '16 at 12:49
6

I got this error when trying to do something like:

$stmt = $pdo->prepare("select name from mytable where id = :id");
$stmt->execute([
  'id' => $id,
  'unusedvar' => $foo, // This row causes the error.
]);

Basically, you can't have unused parameters in the array passed to execute(). Every value in the array passed to execute() must be used in your prepared statement.

This is also specified in the docs:

Binding more values than specified is not possible; if more keys exist in input_parameters than in the SQL specified in the PDO::prepare(), then the statement will fail and an error is emitted.

Lars Nyström
  • 5,786
  • 3
  • 32
  • 33
5

May be you are trying to bind a param within single quotes instead of letting it does the work for you.

Compare:

Model::model()->findAll("t.description ilike '%:filter%'", array(':filter' => $filter));

With:

Model::model()->findAll("t.description ilike :filter", array(':filter' => '%' . $filter . '%'));
Alan Willms
  • 459
  • 1
  • 5
  • 7
5

A cause of this error for me not covered above is when you're dealing with a dynamic array of parameters if you unset any params, you need to reindex before passing them in. The brutal part of this is that your error log doesn't show indexes so it looks like everything is right. Eg:

SELECT id WHERE x = ?, y = ?, z = ?

Might produce the Log: Invalid parameter number: parameter was not defined with params ("x","y","z")

This looks like it shouldn't be throwing an error, but if the indexes are something like:

0 => x, 1 => y, 4 => z

It considers the last parameter undefined because it's looking for key 2.

jtubre
  • 669
  • 1
  • 8
  • 13
  • 1
    Adding to your answer that a simple print_r will show the indexes and that can be fixed with array_values as it will reindex the array starting at 0 – chifliiiii Sep 06 '16 at 17:28