2017-03-06 34 views
0

我是OOP和PHP的新手,所以我在这里遇到问题。有人能告诉我,我的连接类错了吗?它没有连接到数据库,我尝试在try语句中使用var_dump($ this),但它不起作用。此外,我改变我的“DBNAME”一个随机名称和代码仍然“作品” ..为什么连接类不能建立连接?

这里是我的代码:

<?php 
    class connection { 
     // Setting Database Source Name (DSN) 
     public function __construct() { 
      $dsn = 'mysql:host=localhost;dbname=employee'; 
      // Setting options 
      $options = array (PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); 
      // Making the connection to the database 
      try { 
       $this->dbh = new PDO($dsn, 'root', '', $options); 
      } 
      catch (PDOException $e) { 
       $this->error = $e->getMessage(); 
      } 
     } 
    } 
    $connection = new connection(); 
?> 
+1

在'catch'中尝试'echo $ e-> getMessage();'以查看错误详细信息。它的工作原因是try catch块 – codtex

+0

您应该先启用显示错误。您的课程属性尚未定义。 – Raptor

+0

,并放在脚本'error_reporting(E_ALL);'和 'ini_set(“display_errors”,1);' – codtex

回答

0

每种方法在课堂上有返回的东西。 尝试:

class Connection { 

    private $connection;  
    // Setting Database Source Name (DSN) 
    public function __construct() { 
     $dsn = 'mysql:host=localhost;dbname=employee'; 
     // Setting options 
     $options = array (PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); 
     // Making the connection to the database 
     try { 
      $this->connection = new PDO($dsn, 'root', '', $options); 
     } 
     catch (PDOException $e) { 
      $this->error = $e->getMessage(); 
     } 
    } 

    public function DoSomething() 
    { 
     //do something with your $this->connection and return some value; 
    } 
} 
$connection = new Connection(); 
echo $connection->DoSomething(); 
+0

命名约定:最好用大写字母 – Raptor

+1

开始一个类名,这个“答案”本质上是无用的。 –

+0

^true,edited-- – xxx