2016-07-07 10 views
-2

に変換することができませんでしたPDO接続を確立しようとしたとき、私は、このエラーメッセージが出ています。class 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ラインです。コンストラクタは何を持っているに加えて

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 
     } 
    } 
} 

、返却値:

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
は以下への接続の設定を変更しない

:念のために、私はconnect()メソッドにアクセスするコードを挿入します副作用(法律で起訴すべきである)。

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

関連する問題