在非对象PDO上调用成员函数fetchColumn()

时间:2013-04-16 11:28:18

标签: php pdo

尝试获取项目的列,从未在PDO中这样做,尝试查看文档,但它并没有真正帮助。

  $sql = $CONNECT_TO_DATABASE->query("SELECT COUNT(*) FROM comments");
    $result = $sql->fetch(PDO::FETCH_ASSOC);
    $r = $result->fetchColumn();

我做错了什么?

致命错误:在第6行的C:\ xampp \ htdocs \ project \ events.php中的非对象上调用成员函数fetchColumn()

$r = $result->fetchColumn();

谢谢!

连接:

<?php
/**
* Connect to Database
* @Author Jony <artemkller@gmail.com>
**/
    ##################CHANGE THIS####################
        /**                                         #   
        * MYSQL HOST HERE (Example: localhost)      #
        **/                                         #
                                                    #
        DEFINE ("MYSQL_HOST", "localhost");         #
                                                    #
        /**                                         #
        * MYSQL USER HERE (Example: root)           #
        **/                                         #
                                                    #
        DEFINE ("MYSQL_USER", "root");              #
                                                    #   
        /**                                         #       
        * MYSQL PASSWORD HERE (Example: password)   #
        **/                                         #           
                                                    #   
        DEFINE ("MYSQL_PASSWORD", "");              #
                                                    #   
    #################################################

    # Connect to the database using PDO.
    $CONNECT_TO_DATABASE = new PDO('mysql:host='.MYSQL_HOST.';dbname=project', MYSQL_USER, MYSQL_PASSWORD);

    # See if theres an error while connecting to the database
    try {
        $CONNECT_TO_DATABASE->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $ERROR_MESSAGE)
    {
        echo 'ERROR: ' . $ERROR_MESSAGE->getMessage();
    }


?>

2 个答案:

答案 0 :(得分:6)

您的$result变量仅仅是数组,并且没有任何方法。

您不需要第二次提取呼叫。使用fetch或fetchColumn。在你的情况下你需要一个后者:

$sql = $CONNECT_TO_DATABASE->query("SELECT COUNT(*) FROM comments");
$count = $sql->fetchColumn();

顺便问一下,你不觉得$CONNECT_TO_DATABASE有点长吗?如果改为$pdo呢?

当您发布连接代码时,以下是必须的:

# Set PDO connection options
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
# Connect to the database using PDO.
$dsn = 'mysql:host='.MYSQL_HOST.';dbname=project';
$pdo = new PDO($dsn, MYSQL_USER, MYSQL_PASSWORD);

这就是全部。 PHP已经可以处理echo 'ERROR:业务。无需干预

答案 1 :(得分:0)

试试这个假设你的PDO结构是准确的。

 $sql = $CONNECT_TO_DATABASE->prepare("SELECT COUNT(*) FROM comments"); // Prepare your query with PDO
 $sql->execute(); // Once it is prepared execute it

    if ($sql) { // Check if $sql is executed will return TRUE or FALSE
        if ($sql->rowCount() > 0 ) { // If you get any rows back then
           $r = $sql->fetchColumn(); // Get your results
        }
    }