0

this is my connection.php file

<?php

class Connection {

    public $db_host = 'localhost';
    public $db_user = 'root';
    public $db_pass = '';
    public $db_name = 'lybri';

    public function connect() {

        $this->connect_db = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);

        if (mysqli_connect_errno()) {
            printf("Connection failed: %s\n", mysqli_connect_error());
            exit();
        }
        return true;
    }

    public function get_connection() {
        return $this->connect_db;
    }

}

$db = new Connection('localhost', 'user', 'pass', 'name');
$db->connect();
$connection = $db->get_connection();

this script is working without any errors.

and when I need to run a mysql query in another file I just include this connection.php file in to that file and doing like this.

mysqli_query($connection, "SELECT * FROM users WHERE username = '$username' AND password = '$hashedPassword' ");

I just need to know, Is this the best practice to do so.

Thank You.

Yasitha
  • 901
  • 2
  • 17
  • 42

1 Answers1

2

Yes it is the best practice and I believe many people include the connection.php like this only (me too).

But what I have to say on this is use mysqli_real_escape_string to prevent mysql injection attack. (not recommended) OR USE PDO/mysqli

Use it like this mysqli_real_escape_string($db,$id) before your query:

$username=mysqli_real_escape_string($db,$username);
$password=mysqli_real_escape_string($db,$password);
Community
  • 1
  • 1
ɹɐqʞɐ zoɹǝɟ
  • 4,342
  • 3
  • 22
  • 35