2017-01-24 8 views
0

にヌル上)(準備メンバ関数を呼び出して、私はPHPでのログインとPDOを作成しようとしているが、私は致命的なエラー:PDO

Fatal error: Call to a member function prepare() on null in DBOperations.php on line 23

全体の時間を取得します。私はインターネット上の解決策を探していましたが、私は持っていなかったいくつかのエラー、例えばFatal error Call to a member function prepare() on nullを見つけました。誰か助けてくれますか?

Constants.php:

<?php 

define('DB_NAME', 'roedel'); 
define('DB_USER', 'root'); 
define('DB_HOST', 'localhost'); 
define('DB_PASS', ''); 

?> 

DBConnect.php:

<?php 

class DBConnect { 

    private $con; 

    function __construct() { 

    } 

    function connect() { 

     require_once dirname(__FILE__).'/Constants.php'; 

     try{ 

      $this->con = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS); 

     } catch (Exception $ex) { 

      echo "No connection. Try again!" . $ex; 

     } 



    }  
} 

?> 

DBOperations.phpは:

<?php 

class DBOperations { 

    private $con; 

    function __construct() { 

     require_once dirname(__FILE__).'/DBConnect.php'; 

     $db = new DBConnect(); 

     $this->con = $db->connect(); 

    } 

    function createUser($name, $pass, $email){ 

     $password = md5($pass); 

     $rank = "lid"; 

     $stmt = $this->con->prepare("INSERT INTO 'users' ('id', 'name', 'password', 'email', 'rank') VALUES (NULL, ?, ?, ?, ?)"); 
     $stmt->bindParam(1, $name); 
     $stmt->bindParam(2, $password); 
     $stmt->bindParam(3, $email); 
     $stmt->bindParam(4, $rank); 

     if ($stmt->execute()){ 

      return true; 

     }else{ 

      return false; 

     } 


    } 

} 

?> 
+1

mysqlへの接続に失敗している必要があります。 ''接続していません。もう一度やり直してください! ' 。 $ ex; '?例外を 'createUser'の中で例外を発生させてみてください。 – smarber

答えて

0

それはつまり、変数(ここではすなわちDBOperations :: CON)無効である。ここでは、より慎重にあなたのコードで

ルック:ここ

$this->con = $db->connect(); 

、あなたはDBCONNECTを期待::接続を返すように()の接続が、それは何も(実際には、それは「リターン」null)を返しません。 。

あなたがするDBConnectに命令return $this->con;を逃す::(接続)

また、あなたは必要と内側__construct()(またはその他の機能)を設定しますが、ファイルの先頭にshould'nt。 ;)

EDIT:あなたが書くことができ

if ($stmt->execute()){ 
    return true; 
}else{ 
    return false; 
} 

return $stmt->execute(); 

を、それがすでにtrueまたはfalseを返しますので の代わりに。 ;)

+0

ありがとうございました!今私はエラーは表示されませんが、$ stmt-> execute();を返します。 falseを返します。私の新しい問題を手伝ってくれますか? – JvdB100

+0

'setAttribute(PDO :: ATTR_ERRMODE、PDO :: ERRMODE_EXCEPTION);または[Manual error management]オプションで[Exception](http://php.net/manual/fr/pdo.setattribute.php) (http://php.net/manual/fr/pdostatement.errorinfo.php) – zenko