2013-03-16 72 views
0

我想從數據庫中顯示一些信息,並且我有以下兩個文件。當我運行index.php,我得到這個錯誤:Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\pc\index.php on line 16PHP PDO致命錯誤:調用成員函數prepare()

你能告訴我怎麼解決這個問題

的index.php

include_once('database.php'); 

$db= new database(); 
$conn = $db->connect(); 
         //Problem is in the folloing line 
$query = $conn->prepare('SELECT * FROM admin WHERE admin_id = :id'); 
$query->execute(array('id' => 1)); 
?> 
<table> 
<tr> 
<th>Name</th> 
<th>Email</th> 
</tr> 

<?php 
while($rows = $query->fetch(PDO::FETCH_ASSOC)) { 
    echo "<tr>"; 
    echo "<td>". $rows['admin_name'] ."</td>" ; 
    echo "<td>". $rows['admin_email'] ."</td>" ; 

    echo "</tr>"; 
} 
?> 

</table> 

database.php中

class Database{ 

private $host = 'localhost'; 
private $dbname = 'school'; 
private $username = 'root'; 
private $password =''; 

public $con = ''; 

function __construct(){ 

    $this->connect(); 

} 

function connect(){ 

    try{ 

     $this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password); 
     $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); 


    }catch(PDOException $e){ 

     echo 'We\'re sorry but there was an error while trying to connect to the database'; 
     file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND); 

    } 
} 
} 

回答

2
class Database{ 

private $host = 'localhost'; 
private $dbname = 'school'; 
private $username = 'root'; 
private $password =''; 

public $con = ''; 

function __construct(){ 

    $this->connect(); 

} 

function connect(){ 

    try{ 

     $this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password); 
     $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); 


    }catch(PDOException $e){ 

     echo 'We\'re sorry but there was an error while trying to connect to the database'; 
     file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND); 

    } 
    return $this->con; // This makes all the magic!!! 
} 
} 
+1

非常感謝您的回答。這確實是一個神奇的:)如果你不介意..你能告訴我如何停止加載'$ conn = $ db-> connect();'在index.php後面的代碼如果連接出現問題db?謝謝:) – 2013-03-16 06:01:52

+2

@black_belt在'catch'塊內你可以'死('失敗');'或者你想這樣做,否則,檢查'$ conn'是'PDO'的'is_a' if' !$ conn = $ db-> connect();' – Jon 2013-03-16 07:07:34

+0

@Jon!is_a($ conn,'PDO')){/ * kill here * /}'非常感謝。你的解決方案工作完美:)再次感謝人。 :) – 2013-03-16 15:20:12

相關問題