doujian4752 2013-03-16 05:41
浏览 73
已采纳

PHP PDO致命错误:调用成员函数prepare()

I am trying to display some information from database and I have the following two files. When I run the index.php , I get this error:Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\pc\index.php on line 16

Could you please tell me how to solve this problem

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);

    }
}   
}
  • 写回答

1条回答 默认 最新

  • doumeilmikv7099 2013-03-16 05:44
    关注
    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!!!
    }   
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#linux#的问题(输入输出错误):出现这个界面接着我重新装系统,又让修电脑的师傅帮我扫描硬盘(没有问题)用着用着又卡死(相关搜索:固态硬盘)
  • ¥15 cv::resize不同线程时间不同
  • ¥15 web课程,怎么做啊😭没好好听课 根本不知道怎么下手
  • ¥15 做一个关于单片机的比较难的代码,然后搞一个PPT进行解释
  • ¥15 python提取.csv文件中的链接会经常出现爬取失败
  • ¥15 数据结构中的数组地址问题
  • ¥15 maya的mel里,怎样先选择模型A,然后利用mel脚本自动选择有相同名字的模型B呢。
  • ¥15 Python题,根本不会啊
  • ¥15 会会信号与系统和python的来
  • ¥15 关于#python#的问题