2017-03-06 94 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