-1

我正在尝试将我的代码转换为PDOfrom 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();
}

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

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

提前致谢

4

2 回答 2

2

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

在你的connect.php

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

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

于 2012-07-31T15:35:38.430 回答
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);
于 2012-07-31T15:39:46.133 回答