如何在PDO语句上修复此错误:参数号无效?

时间:2014-09-29 22:06:56

标签: php mysql pdo

我正在使用以下代码尝试PDO:

<?php

include('connection.php');

# cartexe.php will perform all actions on cart.php

// add Item to Cart
if(isset($_POST['addItemToCart']))
{
    // initialize index.php variables
    $productName = $_POST['productName'];
    $price = $_POST['price'];
    $description = $_POST['description'];

    // check the cart table to see if the product has been previously added
    $smtp = $conn->prepare('SELECT Quantity FROM cart WHERE Product Name = :product'); // prepare a statement to fetch the quantity for a particular product... the statement is not executed but merely prepared to do so. 
    $smtp->bindParam(':product', $productName, PDO::PARAM_STR); //bind the productName with whatever data supplied hence the statement after : above will be replaced with the actually data.. In additional the statement is set as string hence PDO::PRAM_STR
    $smtp->execute();//finally run the statment

    $result = $smtp->fetch(PDO::FETCH_NUM);

    if($result > 0)
   {
     echo " DATA FOUND";
   }
   else
   {
      echo ' No data founded';
   }

}

?>


但我一直收到以下错误。我尝试了几种不同的方法,但都没有。

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined'

1 个答案:

答案 0 :(得分:3)

将列名包装在反引号中,因为它包含空格

WHERE `Product Name`

在连接打开后立即使用$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);会发出错误信号。

另一种选择是在将列重命名/更改为Product_Name时使用单词之间的下划线

WHERE Product_Name ...

洞察力:

还要确保您的表单元素确实已命名。

I.e。:

<input type="text" name="productName">

使用error reporting并放在文件的顶部:

error_reporting(E_ALL);
ini_set('display_errors', 1);
如果是这种情况,

也会发出(其他)可能的错误信号。