PDO绑定Param麻烦

时间:2012-07-31 15:31:22

标签: php pdo

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

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();
}

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

“服务器错误。网站在检索时遇到错误.......”

提前致谢

2 个答案:

答案 0 :(得分:2)

您需要设置PDO error mode以产生异常,然后才能捕获它们。

connect.php

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

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

答案 1 :(得分:1)

请尝试使用此选项以查看是否从查询中返回有效对象。

    // 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);