PDO - "调用非对象上的成员函数fetch()"

时间:2015-04-10 12:58:41

标签: php mysql pdo

我知道通常在查询返回false时会发生错误,但这次没有理由发生! (或者我只是犯了一个大错误)

    if(!$security_SenderId){
        $getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = '?'");
        $getbaseticket = $getbaseticketqry->execute(array($ticket_safeid));
    }else{
        $getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = '?' AND `ticket_sender` = '?'");
        $getbaseticket = $getbaseticketqry->execute(array($ticket_safeid, $security_SenderId));
    }

    if($getbaseticket === false){
        return false;
    }else{
        $baseticket = $getbaseticket->fetch(PDO::FETCH_ASSOC);
    }

我在一个函数中使用了这些函数,它将支持票据信息作为数组返回,但正如我所说,当我尝试获取票证信息时会发生错误。我试图通过启用pdo调试模式db->errorInfo()来检查获取行之前的mysql错误,但它不起作用。

这里有什么问题?

编辑:

<?php
error_reporting(E_ALL); ini_set('display_errors', 1);

class TICKET_MANAGER
{
    function __construct($dbhost, $dbname, $dbuser, $dbpass) {
        try{
            $this->db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }catch(PDOException $e){
            die('Connection failed: ' . $e->getMessage() );
        }
    }

    function viewTicket($ticket_safeid, $security_SenderId = false)
    {
        try{
            if(!$security_SenderId){
                $getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = ?");
                $getbaseticket = $getbaseticketqry->execute(array($ticket_safeid));
            }else{
                $getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = ? AND `ticket_sender` = ?");
                $getbaseticket = $getbaseticketqry->execute(array($ticket_safeid, $security_SenderId));
            }
        }catch(PDOException $e){
            die('Mysql error: ' . $e->getMessage() );
        }
        ...

    }

    ...
}

1 个答案:

答案 0 :(得分:3)

这是所有'?'周围的引号 - 删除它们。

阅读手册

来自手册:

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");

异常应该告诉你错误

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)

并在连接到数据库后立即使用。


- http://php.net/manual/en/pdo.error-handling.php

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

查询:

try {

// your query

}
    catch(PDOException $e){
     print  $e->getMessage();
    }

error reporting添加到文件的顶部,这有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

旁注:错误报告应仅在暂存时完成,而不是生产。