我的PDO预备声明出了什么问题?

时间:2013-08-16 15:12:15

标签: php pdo

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

由于构建新连接和查询脚本,我不断抛出此错误

  

警告:PDOStatement :: execute():SQLSTATE [HY093]:参数号无效:参数未在第31行的D:\ wamp \ www \ Kerr Pumps \ includes \ product_data.php中定义

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

// 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的新手并且可能错过了一些简单的内容,任何反馈或指示都会非常感谢,谢谢。

1 个答案:

答案 0 :(得分: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
相关问题