好的,我遇到了一个非常奇怪的PDOException,我似乎无法让我的头。下面是生成的异常:
PDOException: SQLSTATE[IMSSP]: Tried to bind parameter number 65536. SQL Server supports a maximum of 2100 parameters. in D:\Work\CEUR16-004\Project\www_root\includes\scripts\php\libCore\products.php:169
Stack trace:
#0 D:\Work\CEUR16-004\Project\www_root\includes\scripts\php\libCore\products.php(169): PDOStatement->execute()
#1 D:\Work\CEUR16-004\Project\www_root\includes\pages\products\products.php(5): ProductCore->build_product_list()
#2 D:\Work\CEUR16-004\Project\www_root\index.php(27): include('D:\\Work\\CEUR16-...')
#3 {main}
下面是它所指的代码:
public function build_product_list()
{
// This function builds the product list visible on the main site (guests only)
try
{
if($this->product_type_id == "999")
{
$query = 'SELECT sp.product_id, sp.product_name, sp.product_price, pt.product_type_name FROM shop_products AS sp LEFT JOIN product_types AS pt ON sp.product_type_id = pt.product_type_id ORDER BY sp.product_type_id ASC'; // Line 161
}
else
{
$query = 'SELECT sp.product_id, sp.product_name, sp.product_price, pt.product_type_name FROM shop_products AS sp LEFT JOIN product_types AS pt ON sp.product_type_id = pt.product_type_id WHERE sp.product_type_id = :product_type_id ORDER BY sp.product_id ASC';
}
$stmt = $this->dbcore_prod_core->dbc->prepare($query);
$stmt->bindParam(':product_type_id', $this->product_type_id, PDO::PARAM_INT);
$stmt->execute(); // Line 169
// Function continues below...
现在,只有当$this->product_type_id
等于在第161行上运行查询的999
(在上面的代码中注释)时,才会生成此异常。我已经在服务器上直接运行了查询,它返回预期的结果,那么为什么PDO会抛出一个异常呢?
发布于 2017-05-04 23:54:19
我花了几分钟才发现自己做错了什么,但是很快它就点击了,我试图将product_type_id
绑定到一个占位符,这个占位符在第161行调用的查询中不存在,但在第166行的查询中存在。因此,如果$this->product_type_id
等于999
,则PDO会由于试图绑定到第161行的查询而抛出一个异常,但其他任何时候都会正常工作,因为它将试图在第166行上运行查询。这就需要对代码进行轻微调整,如下所示:
public function build_product_list()
{
// This function builds the product list visible on the main site (guests only)
try
{
if($this->product_type_id == "999")
{
$query = 'SELECT sp.product_id, sp.product_name, sp.product_price, pt.product_type_name FROM shop_products AS sp LEFT JOIN product_types AS pt ON sp.product_type_id = pt.product_type_id ORDER BY sp.product_type_id ASC'; // Line 161
$stmt = $this->dbcore_prod_core->dbc->prepare($query);
}
else
{
$query = 'SELECT sp.product_id, sp.product_name, sp.product_price, pt.product_type_name FROM shop_products AS sp LEFT JOIN product_types AS pt ON sp.product_type_id = pt.product_type_id WHERE sp.product_type_id = :product_type_id ORDER BY sp.product_id ASC';
$stmt = $this->dbcore_prod_core->dbc->prepare($query);
$stmt->bindParam(':product_type_id', $this->product_type_id, PDO::PARAM_INT);
}
$stmt->execute(); // Line 169
// Function continues below...
对于每个条件,将准备查询。然后,如果调用第二个查询而不是第一个查询,那么它将仅在此时绑定参数。
https://stackoverflow.com/questions/43794441
复制相似问题