2013-12-20 222 views
0

我有一個連接類文件,它允許我的其他類「函數」連接到我的MySQL數據庫。但是,當我執行MySQL查詢時,它僅返回Array()。我選擇的數據其實就在那裏(我查過)。問題是什麼?PDO查詢返回空

Connection.php

<?php 

class Connection extends PDO { 

private $username; 
private $password; 
private $database; 
private $hostname; 

public function __construct($hostname, $username, $password, $database) { 

    $this->hostname = $hostname; 
    $this->username = $username; 
    $this->password = $password; 
    $this->hostname = $hostname; 

    try { 
     parent::__construct("mysql:host=" . $this->hostname . ";dbname=" . $this->database, $this->username, $this->password); 
    } 

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

?> 

的functions.php

<?php 

require_once "Connection.php"; 

class Functions { 

private $connection; 

public function __construct() { 
    $this->connection = new Connection("127.0.0.1", "xxx", "xxx", "xxx"); 
} 

public function sqlFetchAssoc($query) { 

    $sth = $this->connection->prepare($query); 
    $sth->execute(); 
    $result = $sth->fetchAll(PDO::FETCH_ASSOC); 

    return $result; 
    } 
} 

$functions = new Functions(); 
$row = $functions->sqlFetchAssoc("SELECT * FROM chatlogs WHERE id = 70"); 

print_r($row); 

?> 
+0

你應該在那裏添加更多的錯誤檢查。看看你是否在某處發生錯誤。 –

+1

你爲什麼不直接使用PDO對象呢? –

+0

http://www.php.net/manual/en/pdo.errorinfo.php –

回答

0

我發現你在Connection.php錯誤:

$this->hostname = $hostname; 
$this->username = $username; 
$this->password = $password; 
$this->hostname = $hostname; 

$this->hostname重複$this->database未設置。但是,您可以完全剝離設置$this->something,因爲您在相同的功能中使用這些值。這將使它更簡單:

try { 
    parent::__construct("mysql:host=" . $hostname . ";dbname=" . $database, $username, $password); 
} 

我建議更進一步。你應該分別測試測試。您可以在testfunction.php寫這個劇本並調試它(如果需要):

<?php 
class Functions { 
private $connection; 

public function __construct() { 
    $this->connection = new PDO("mysql:host=127.0.0.1;dbname=xxx", "xxx", "xxx"); 
} 

public function sqlFetchAssoc($query) { 

    $sth = $this->connection->prepare($query); 
    $sth->execute(); 
    $result = $sth->fetchAll(PDO::FETCH_ASSOC); 

    return $result; 
    } 
} 

echo "Test started <br><br>"; 
echo "Initialization: <br>"; 
$functions = new Functions(); 
echo "Correct<br><br>"; 
echo "Performing a select: <br>"; 
$row = $functions->sqlFetchAssoc("SELECT * FROM chatlogs WHERE id = 70"); 
print_r($row); 
echo "Test finished."; 
?> 

然後做一流的類似的東西。那麼不僅可以更容易地發現錯誤,而且如果發生錯誤,您可以參加這些測試,看看出了什麼問題,而不是再次寫出錯誤。切記不要將它們包含在生產代碼中。

+1

確實非常尷尬的錯誤!這似乎解決了它。非常感謝。 – user2879373

+1

如果你打算重用這段代碼,我還建議默認設置'charset = utf8'。別客氣 (: –