2014-09-29 99 views
0

我想一个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' 

回答

3

在反引号包装你列的名称,因为它包含空格

WHERE `Product Name` 

有使用$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);打开连接之后,就已经暗示了错误。

另一种选择是,同时重命名/改变你列Product_Name

WHERE Product_Name ... 

见识使用单词之间的下划线:

另外,还要确保你的表单元素的确命名。

即:

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

使用error reporting并放置在您的文件(S)的顶部:

error_reporting(E_ALL); 
ini_set('display_errors', 1); 

将信号(其他)可能的错误也,它应该是案件。

+1

谢谢,感激! – TheAmazingKnight 2014-09-29 22:16:33

+0

@TheAmazingKnight不客气。 – 2014-09-29 22:16:43

相关问题