简体   繁体   中英

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->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 ).

否则,您可以执行die($select)来查看生成的SQL语句。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM