0

尝试为我的项目获取列,从未在 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();
    }


?>
4

2 回答 2

6

您的$result变量只是一个数组,没有任何方法。

您不需要第二次 fetch 调用。使用 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:业务。无需干预

于 2013-04-16T11:33:47.740 回答
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
        }
    }
于 2013-04-16T11:36:13.340 回答