PDO绑定参数故障


PDO Bind Param Trouble

我正在尝试将代码从mysql_query转换为PDO,并从这个函数开始

function label_for_field($field_name, $table_name) {
        $table = array();
        // Bind variables to parameters
        $param_array = array(':bundle' => $table_name, ':field_name' => $field_name);
        // Prepare Query Statement
        $query = "SELECT data FROM field_config_instance WHERE bundle = :bundle AND field_name = :field_name";
        $STH = $DBH -> prepare($query);
        // Execute
        $STH -> execute($param_array);
        // Set the fetch mode
        $STH -> setFetchMode(PDO::FETCH_OBJ);
        while ($row = $STH -> fetch()) {
            $info = unserialize($row -> data);
            $table[] = $info['label'];
        }
        return $table[0];
    }

我试着输出它,看看它是否能正常

include_once ("includes/connect.php");
include ("includes/functions.php");
echo label_for_field("field_account_number", "account_table");

这是connect.php

// Include Constants
require_once ("constants.php");
//Establish Connection
try {
    $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch (PDOException $e) {
    echo $e -> getMessage();
}

我不知道是不是因为我绑定了错误的参数,它只是给了我一个服务器错误页面

"服务器错误。网站在检索时遇到错误……"

提前感谢

您需要设置PDO错误模式以生成异常,然后才能捕获它们。

在您的connect.php:中

try {
    $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
}

然后,您可以在函数中使用与连接文件类似的try/catch语句,并使用它来显示开发环境中的错误。

试着这样做,看看是否从查询中返回了有效的对象。

    // Prepare Query Statement
    $query = "SELECT data FROM field_config_instance WHERE bundle = :bundle AND field_name = :field_name";
    $STH = $DBH -> prepare($query);
    $STH->bindValue(":bundle", $table_name);
    $STH->bindValue(":field_name", $field_name);
    $STH->execute();
    $STH->setFetchMode (PDO::FETCH_OBJ);
    $result = $STH->fetchAll();
    var_dump($result);