2016-07-07 140 views
-2

我越來越想做一個PDO連接時,此錯誤消息:對象無法轉換爲字符串

dbConnection類的對象無法轉換爲字符串(行)

這是我的代碼:

class dbConnection 
{ 
    protected $db_conn; 
    public $db_name = "todo"; 
    public $db_user = "root"; 
    public $db_pass = ""; 
    public $db_host = "localhost"; 

    function connect() 
    { 
     try { 
      $this->db_conn = new PDO("mysql:host=$this->$db_host;$this->db_name", $this->db_user, $this->db_pass); 
      return $this->db_conn; 
     } 
     catch (PDOException $e) { 
      return $e->getMessage(); 
     } 
    } 
} 

的錯誤是在PDO線。爲以防萬一,我插在那裏我接觸到connect()方法的代碼:

class ManageUsers 
{ 
    public $link; 

    function __construct() 
    { 
     $db_connection = new dbConnection(); 
     $this->link = $db_connection->connect(); 
     return $link; 
    } 

    function registerUsers($username, $password, $ip, $time, $date) 
    { 
     $query = $this->link->prepare("INSERT INTO users (Username, Password, ip, time1, date1) VALUES (?,?,?,?,?)"); 
     $values = array($username, $password, $ip, $time, $date); 
     $query->execute($values); 
     $counts = $query->rowCount(); 
     return $counts; 
    } 
} 

$users = new ManageUsers(); 
echo $users->registerUsers('bob', 'bob', '127.0.0.1', '16:55', '01/01/2015'); 
+1

Nopes ...您的問題沒有包含正確的行。 –

+0

它包含我擁有的所有代碼... @PraveenKumar – Adir

+0

爲什麼你在構造函數中返回一些東西? – apokryfos

回答

1

更改連接設置爲以下內容:

class dbConnection 
{ 
    protected $db_conn; 
    public $db_name = "todo"; 
    public $db_user = "root"; 
    public $db_pass = ""; 
    public $db_host = "localhost"; 

    function connect() 
    { 
     try { 
      $this->db_conn = new PDO("mysql:host={$this->db_host};{$this->db_name}", $this->db_user, $this->db_pass); //note that $this->$db_host was wrong 
      return $this->db_conn; 
     } 
     catch (PDOException $e) { 
      //handle exception here or throw $e and let PHP handle it 
     } 
    } 
} 

此外,返回值在構造函數沒有副作用(應該由法律起訴)。

0

請按照以下代碼,在我的服務器上測試並運行良好。

class Config 
    { 
    var $host = ''; 
    var $user = ''; 
    var $password = ''; 
    var $database = ''; 

    function Config() 
    { 
     $this->host  = "localhost"; 
     $this->user  = "root"; 
     $this->password = ""; 
     $this->database = "test";  
    } 

} 

function Database() 
{ 
     $config = new Config(); 

     $this->host = $config->host; 
     $this->user = $config->user; 
     $this->password = $config->password; 
     $this->database = $config->database; 
} 

function open() 
{ 

    //Connect to the MySQL server 
    $this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->database, $this->user,$this->password); 
    if (!$this->conn) 
    { 
     header("Location: error.html"); 
     exit; 
    } 

    return true; 
} 
+0

你從哪裏得到配置? – Adir