2013-03-16 43 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

相关问题