开发者

ZF: query error SQLSTATE[HY093]

I have error on this function:

public function getCountCategoryByUrl($url, $root = 0)
{
    $url = strtolower($url);


    $select = $this->select()
                   ->from($this->_name, array('count(*) as cnt'))
                   ->where("LOWER(catalog_url) LIKE :url " . ($root > 0 ? " AND `type` = :type" : ""));

    return $this-开发者_JAVA技巧>getAdapter()->fetchOne($select, array('url' => $url, 'type' => $root));
}

Error:

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

What I'm doing wrong?


The problem arises when you have $root <= 0. In this case your SQL statement contains only one token (:url) while you're binding two variables (:url and :type).

You have to set the bound parameters conditionally:

$select = $this->select()
               ->from($this->_name, array('count(*) as cnt'))
               ->where("LOWER(catalog_url) LIKE :url ");
$params = array(':url' => $url);
if ($root > 0) {
    $select->where("`type` = :type");
    $params[':type'] = $root;
}

return $this->getAdapter()->fetchOne($select, $params);

EDIT: I've overlooked something very important. Variables must be bound with the same token as defined in the SQL statement. This means that you have to use :url and :type for the bound variables (not url and type).


Else, you can do die($select) to view what SQL statement is generated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜