How does a colon (:) preceding a variable name within quotes work?

php, yii

Solution

The colon doesn't have any special meaning. The pattern `:parent_id` as a whole does, but that's only because you chose to use it as a variable name in the `WHERE` condition (`parent_id=:parent_id`).

You could just as well have chosen to write

$data=Location::model()->findAll('parent_id=the_quick_brown_fox',
     array('the_quick_brown_fox'=>(int) $_POST['Current-Controller']['country_id']));

In practice the colon is used because there's the risk of the name you choose for the variable also being present as a legitimate part of the condition, in which case all instances of it will be replaced with the value and results will be unexpected.

For example, this:

$data=Location::model()->findAll('parent_id=parent_id',
     array('parent_id'=> 1 /*anything, really*/));

would result in the condition `1=1`, which would match all records.

Problem

I assume that `:parent_id` evaluates to a number. But, how exactly does this piece of code work? When should I use this syntax (`:name`)? ``` $data = Location::model()->findAll('parent_id=:parent_id',array( ':parent_id' => (int) $_POST['Current-Controller']['country_id'] )); ```

Original source