PHP PDO不从其他类返回任何数据

时间:2013-11-08 18:16:38

标签: php class pdo

我有以下脚本根本没有返回任何东西,我得到的最好的是一个var_dump来表示bool(false)..我的error_log中什么也没有,并且没有抛出任何异常:< / p>

的index.php:

require("php/bootstrap.php");
$campaign = new Campaign($_GET['campaign'], $mysql);

bootstrap.php中:

define ("MYSQL_USER", "specialagent");
define ("MYSQL_PASS", "supertopsecret");
define ("MYSQL_HOST", "127.0.0.1");
define ("MYSQL_PORT", "3306");
define ("MYSQL_DB", "databasewithsecretinformation");


/* Auto include classes on instantiation */
function __autoload($class_name) {
    include 'classes/'.$class_name.'.php';
}

/* Connections */
try {
$mysql = new PDO("mysql:host=".MYSQL_HOST.";dbname=test", MYSQL_USER, MYSQL_PASS);
} catch(PDOException $e) {
die("There was a problem connecting to the database. Error: " . $e->getMessage());
}

Campaign.php

class Campaign {
protected $dbh;
private $campaign_id = "";
private $name = "";

public function __construct ($campaign_id, PDO $db) {

    //if ($campaign_id) {
        $this->setCampaignID($campaign_id);
        $this->dbh = $db;
        $this->loadCampaignInfo();
    //}
}


public function getCampaignID() {
    return $this->campaign_id;
}

public function setCampaignID($id) {
    $this->campaign_id = $id;
}

public function __destruct() {
    //$this->dbh = null;
}

public function loadCampaignInfo() {
    /* Get info from database */
    $sql = "SELECT * FROM campaigns WHERE campaign=:campaignID";

    try {
        echo "trying query...$sql<br />";
        if ($this->dbh instanceof PDO) {
            $stmt = $this->dbh->prepare($sql);
            $stmt->bindParam(":campaignID", $this->campaign_id, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();

            echo "Returned Data: ";
            var_dump($row);
        } else {
            echo "Not a valid PDO resource";
        }


    } catch (PDOException $e) {
        echo "Problem : " . $e->getMessage;
    } catch (Exception $e) {
        echo "Other problem : " . $e->getMessage;
    }


    /* Set properties */
}

}

输出:

trying query...SELECT * FROM campaigns WHERE campaign=:campaignID
Returned Data: bool(false) 

2 个答案:

答案 0 :(得分:0)

问题与PDO无关 Returned Data: bool(false)表示没有找到符合条件的行 检查您的表格是否包含数据并检查输入 检查你是否从autoload和所有类似的东西中获得了正确的课程。

另外,将引导程序连接更改为

ini_set('display_errors',1);
error_reporting(E_ALL);

/* Connections */
$mysql = new PDO("mysql:host=".MYSQL_HOST.";dbname=test", MYSQL_USER, MYSQL_PASS);
$mysql->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

你也可能希望这个方法不那么臃肿:

/* Get info from database */
public function loadCampaignInfo()
{
    $sql = "SELECT * FROM campaigns WHERE campaign=?";
    $stmt = $this->dbh->prepare($sql);
    $stmt->execute([$this->campaign_id]);
    return $stmt->fetch();
}

答案 1 :(得分:-1)

问题是用户没有正确的权限访问数据库,在您的常识提示信用证问题后,登录到MySQL cli并注意到数据库不在SHOW DATABASES中。

感谢大家的帮助。