1

I have an issue with the code below, so I have created a database connection and running it in CMD appears to be working fine, but I am not 100% how to test it out ? Can someone please point if out if its fine, Im still a newbie in PHP

<?php

class databaseConnection
{
    private $host;
    private $databasename;
    private $username;
    private $password;
    public $mysqli;

    //forcing the data to be given to the object (using the constructor)
    public function __construct()
    {
        $this->databaseConnect();
    }

    private function databaseConnect()
    {
        $this->host = 'localhost';
        $this->username = '$$$$$';
        $this->password = '$$$$$';
        $this->databasename = '$$$$$$$';

        $this->mysqli = new mysqli($this->host, $this->username, $this->password, $this->databasename);
        return $this->mysqli;
        echo('Connection Succeeded');
    }
}
fabpico
  • 2,628
  • 4
  • 26
  • 43
phphero
  • 13
  • 3
  • try getting the class in separate file and using a select statement? – treyBake Jul 23 '18 at 11:09
  • Does this answer your question? [Should we ever check for mysqli\_connect() errors manually?](https://stackoverflow.com/questions/58808332/should-we-ever-check-for-mysqli-connect-errors-manually) – Dharman Apr 27 '20 at 16:49

2 Answers2

-1

try this style for OOP. declare your variable first, like :

$localhost = 'localhost'; 
$user      = 'user'; 
$pw        = 'pass';
$db        = 'database';
$mysqli = new mysqli($localhost,$user,$pw,$db);

For Reference : this

ilham suryoko
  • 55
  • 1
  • 1
  • 9
  • I didn't downvote, but this doesn't actually answer the question... nor does it check if connection is successful .. – treyBake Jul 24 '18 at 12:03
-1

Everything after 'return' won't get executed btw.

You should wrap the '$this->mysqli;' inside an if.

if($this->mysqli){
  echo 'OK';
} else {
  echo 'error';
  echo $this -> mysqli -> error;
}

The mysqli returns a Boolean if the connect was succesful.

To test the actual connection, maybe add a 'test' function that selects 1 record from a default table.

Bert Maurau
  • 979
  • 5
  • 21
  • hi Bert Thanks, tried this out but still cannot see OK or error returned? if ( $this->mysqli){ echo 'OK'; }else { echo 'error'; echo $this -> mysqli -> error; – phphero Jul 23 '18 at 11:33
  • Did you put it before your 'return $this_.mysqli'? Is your databaseConnection() getting initialized somewhere like '$conn = new databaseConnection();' otherwise the constructor won't get triggered? – Bert Maurau Jul 23 '18 at 11:36
  • fixed! Thanks a million :) – phphero Jul 23 '18 at 11:47