PHP Database Connection Class

 

Simple Database Connection Class With PHP

This tutorial is a bare bones login class that can be used to connect to a database so that you can execute custom queries. It consists of two files; one contains the actual Login class while the other file will instantiate a new object and gather a variable from that class.

Rundown

The login class has four private properties; $host, $user, $pw and database. The class also uses the constructor which accepts the four arguments. These argumments are set as the properties.

The non-class file sets values for the variables that are passed into a new instantiated object. The code for this is $login = new Login($host, $user, $pw, $database);

Finally, the $db variable is returned using the db_connect() method. Now, the $db variable can be used to query the database. An example query shows how this occurs.

Login Class(class-login.php)

class Login
{
    private $host;
    private $user;
    private $pw;
    private $database;


    function __construct($host, $user, $pw, $database)
    {
        $this->host = $host;
        $this->user = $user;
        $this->pw = $pw;
        $this->database = $database;
    }


 function db_connect() {
 
 $host = "localhost";
 $user = "user";
 $pw = "password";
 $database = "database_name";

 $db = mysqli_connect($host, $user, $pw, $database) or die("Cannot connect to mySQL."); 

 return $db;
}

}

Other File(login.php)

include("class-login.php");

$host = "localhost";
$user = "username";
$pw = "password";
$database = "database_name";

$login = new Login($host, $user, $pw, $database);

$db = $login->db_connect();

var_dump($db);

$command = "SELECT * FROM tablename ORDER BY id ASC LIMIT 1";
$result = mysqli_query($db, $command);

while ($row = mysqli_fetch_assoc($result)) {
    echo substr($row['name'], 0, 1000);
}