2

I am connecting to a database using a constructor and disconnecting with a destructor. All I want to know is: is it more efficient when I call this from the constructor? What about the destructor? Is it safe or good coding to connect to a database with a prepared statement?

How do I create a method for insertion?

public function __construct($host, $username, $password, $dbname, $tablename="")
        {
            $this->host = $host;
            $this->username = $username;
            $this->password = $password;
            $this->dbname = $dbname;
            $this->tablename = $tablename;
            $this->con = mysqli_connect($host, $username, $password, $dbname); //connecting...

 if(mysqli_connect_errno($this->con))
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    else
    {
    echo "Connection Established<br>";
    } 
}
public function __destruct()
{
    if(mysqli_close($this->con))
    {
        echo "<br>Connection Terminated";
    } 
}
Nick Cox
  • 30,617
  • 6
  • 27
  • 44
GAURAV MAHALE
  • 976
  • 9
  • 16

1 Answers1

1

I would either set the db login data within the __construct, or supply these by default. If you do not you would have to enter the login data every time you create an instance of that class...

public function __construct($host = 'localhost', $username = 'admin', $password = 'admin', $dbname = 'mydatabase' , $tablename="mytable")

You could also set these as class properties. The concept is the same though. You can also separate your SQL connection fro the Class and connect in a different class, and instantiate that class from within your constructor. You might want to put inspiration from this answer.

Community
  • 1
  • 1
edwardmp
  • 5,933
  • 5
  • 41
  • 74