-1

由于我注意到我的站点容易受到 SQL 注入攻击,因此我已从使用标准 mysqli 连接协议切换到 PDO。

自从构建新的连接和查询脚本以来,我不断地抛出这个错误

警告:PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in D:\wamp\www\Kerr Pumps\includes\product_data.php on line 31

尽管访问了其他论坛帖子,但我无法找到解决问题的方法。

// Get a list of all the pumps in the database
function get_pumps( $pType, $pVal, $gVal, $class_style ) {


    // PDO DB CONNECTION AS OF VERSION 1.1

    // Check whether correct data is passed into function...
    echo var_dump($pType);
    echo var_dump($pVal);
    echo var_dump($gVal);   

    // Local connection variables
    $db_user = "root";
    $db_pass = "root";

    // Connect to the database
    try 
    {
        $connection = new PDO('mysql:host=localhost;dbname=kerrpumps', $db_user, $db_pass );
        $stmt = $connection->prepare('SELECT * FROM pumps WHERE pump_type = :pType AND flow_psi = :pVal AND flow_gpm = :gVal AND high_psi = :pVal AND high_gpm = :gVal');
        $stmt->execute(array( 'pump_type' => $pVal, 
                              'flow_psi'  => $pVal, 
                              'flow_gpm'  => $gVal, 
                              'high_psi'  => $pVal, 
                              'high_gpi'  => $gVal ));

        $result = $stmt->fetchAll();

        // If there are results...
        if ( count($result) )
        {
            foreach($result as $row){
                $link = '#';
                echo '<tr onclick="'."$link; window.location='$link'".'" class="'.($class_style %2 == 0 ? "row_dark" : "row_light").'">';
                echo '<a href="#">';
                include("grid_data.php"); 
                echo '</a>';
                $class_style++;
                echo "</tr>"; 
            }
        }

        // Else there are no results which match the query...
        else {
            echo "<tr class='styleOff'>
                    <td class='styleOff'>We're sorry, but there are no pumps which fit the given search criteria. Please try again.</td>
                </tr>";
        }


    } 

    // Error handling
    catch(PDOException $e) {
       echo 'ERROR: ' . $e->getMessage();
    }

}

如上所述,我是 PDO 的新手,可能错过了一些简单的事情,任何反馈或指示将不胜感激,谢谢。

4

1 回答 1

2

您传递给->execute()调用的数组键应与您正在使用的占位符的名称匹配,而不是与占位符进行比较的字段:

SELECT * FROM pumps WHERE pump_type = :pType AND flow_psi = :pVal AND flow_gpm = :gVal AND high_psi = :pVal AND high_gpm = :gVal
                                       ^^^^^---- use this instead

$stmt->execute(array('pType' => 'foo', ....));
                      ^^^^^--- use the placeholder name, NOT the field name
于 2013-08-16T15:15:13.260 回答