1

I am trying to make a user login registration system.All things are going well but when i trying to insert then i get a fatal error and its says

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\LoginRegister\LoginRegistration\functions.php on line 11

I have searched and find some topic which said database variable should be global .But its do not work for me.Can anyone tell me where is the problem?

Thanks in advanced.

Here is my config.php file.

 <?php

 class DatabaseConnection{
   public function __construct(){
    try{
        $db = new PDO('mysql:host=localhost;dbname=phplogin', 'root', '');
    }
    catch (PDOEXCEPTION $e){
        die("ERROR Database Connection:".$e->getMessage());
    }
  }
 }

 ?>

And here is my functions.php file.

 <?php
  require "config.php";

   class LoginRegistration{
   function __construct(){
    $database = new DatabaseConnection();
}
public function resigterUser($username, $password, $name, $email, $website){
    global $db;

    $query = $db->prepare("SELECT id FROM users WHERE username = ? AND  email = ?");
    $query->execute(array($username, $email));
    $num = $query->rowCount();

    if($num == 0){
        $query = $db->prepare("INSERT INTO users (username, password, name, email, website) VALUES (?, ?, ?, ?, ?)");
        $query->execute(array($username, $password, $name, $email, $website));
        return true;

    }
    else{
        return print "<span style='color:#e53d37'>Error... username/email already exist!</span>";
     }
   }
 }
  ?>
Chonchol Mahmud
  • 2,717
  • 7
  • 39
  • 72

2 Answers2

4
class DatabaseConnection{
   public function __construct(){
    try{
        $db = new PDO('mysql:host=localhost;dbname=phplogin', 'root', '');

this assigns the pdo instance to the variable $db in the local scope of the constructor method. Once this method is left, $db becomes unreachable.

You can try something like

<?php
class DatabaseConnectionProvider {
    protected $pdo;
    public function __construct() {
        $this->pdo = new PDO('mysql:host=localhost;dbname=phplogin', 'root', '');
    }

    public function getConnection() {
        return $this->pdo;
    }
}

class LoginRegistration{
    protected $dbp;
    function __construct(DatabaseConnectionProvider $dbp) {
        $this->dbp = $dbp;
    }

    public function registerUser($username, $password, $name, $email, $website) {
      $pdo = $this->dbp->getConnection();
      $query = $pdo->prepare("SELECT id FROM users WHERE username = ? AND  email = ?");
VolkerK
  • 95,432
  • 20
  • 163
  • 226
1

change your config code like this

<?php

class DatabaseConnection{
   public function __construct(){
    try{
        global $db;
        $db = new PDO('mysql:host=localhost;dbname=phplogin', 'root', '');
    }
    catch (PDOEXCEPTION $e){
        die("ERROR Database Connection:".$e->getMessage());
    }
  }
 }

 ?>
Renish Khunt
  • 5,620
  • 18
  • 55
  • 92