PHP connection error with mysqli

After procedural php I study the basic of OOP since last week and tried to connect database. But it shows me unexpected error:

unexpected '$conn' (T_VARIABLE), expecting function (T_FUNCTION)

PHP code:

class Database 
{
   public $conn;

   private $host = "localhost";
   private $user = "root";
   private $pass = "";
   private $db   = "inventory";

   // Create connection
    $conn = new mysqli($host, $user, $pass, $db);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    echo "Connected successfully";
}

Try this :

<?php

class Database {
   public $conn;

   private $host = "localhost";
   private $user = "root";
   private $pass = "";
   private $db   = "inventory";

   public function __construct()
   {
       // Create connection
       $this->conn = new mysqli($this->host, $this->user, $this->pass, $this->db);

        // Check connection
        if ($this->conn->connect_error) {
            die("Connection failed: " . $this->conn->connect_error);
        }
        echo "Connected successfully";
    }

    public function getCon() {
        return $this->conn;
    }

}

?>

You need a constructor. For use your class just :

$oDatabase = new Database();

You need getter for acces at $conn;


You have to store your connection code into a function. Dont forget to remove public $conn; from the top.

  public function createConnection ()
  {
       // Create connection
       $conn = new mysqli($this->host, $this->user, $this->pass, $this->db);

       // Check connection
       if ($conn->connect_error) {
           die("Connection failed: " . $conn->connect_error);
       }

       //echo "Connected successfully";
       return $conn;
   }

Then u can create an object of the class.

  $db = new Database(); // Your main object
  $conn = $db->createConnection(); // The connection object

Note that i've been using $this->variable to access your private variables in your class.

Now you can use the connection object. eg $conn->query("SELECT * FROM MyTable");


Your class doesn't have any function. You need, for example, a connect() to connect to the database.

    class Database {
      // public $conn;

       private $host = "localhost";
       private $user = "root";
       private $pass = "";
       private $db   = "inventory";

       // Create connection
       function connect() {
         $conn = new mysqli($host, $user, $pass,$db);
          // Check connection
          if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
          }
          echo "Connected successfully";
       }
    }
链接地址: http://www.djcxy.com/p/58074.html

上一篇: Javascript非法令牌错误

下一篇: PHP与mysqli的连接错误