Hello I particularly new to PHP programming so here is my problem.
I have a class named Connection. I just wanted to make a connection class where I can instantiate and get a connection right away, also I don't want to filling up the localhost username, password, database every time I make a connection to database so I made this very simple class:
class Connection
{
private $mysqli;
private $filehandle;
private $_isConnected;
private $_isFileLoaded;
public function __construct( $filename )
{
$_isFileLoaded = $this->loadKeyFromFile( $filename );
}
public function __destruct()
{
if( $this->_isConnected )
mysqli_close( $this->mysqli );
}
public function getConnection()
{
return ( $this->_isConnected )? $this->mysqli : false;
}
public function isFileLoaded()
{
return $this->_isFileLoaded;
}
public function isConnected()
{
return $this->_isConnected;
}
private function loadKeyFromFile( $filename )
{
if( !file_exists( $filename ) )
return false;
$filehandle = fopen( $filename , 'r' );
$read = array();
while( $line = fgets( $filehandle ) )
{
$read[] = $line;
}
fclose( $filehandle );
if( count( $read ) == 4 )
{
$localhost = $read[ 0 ];
$username = $read[ 1 ];
$password = $read[ 2 ];
$database = $read[ 3 ];
$this->_isConnected = $this->connect( $localhost ,$username , $password , $database );
return true;
}
else
return false;
}
private function connect($host , $user , $pass , $db )
{
$this->mysqli = mysqli_connect( $host , $user , $pass , $db ) or die( "Database connection failed : " . mysqli_connect_error() );
return ( true )? true : false;
}
}
What I don't understand is that it cannot find the host even though the host is localhost. When I try to change the line: mysqli_connect( 'localhost' , $user , $pass , $db );
It works like a charm! It seems it cannot read the $host variable, I also have the same issue with $user and $pass. On $db I got no problem, it can simply read the name of the database I wanted to select. I have checked the value of $host $user and $pass on their local scope and when they were first read in the function loadKeyFromFile() and it seems they contain the value I really need to start a connection what I just don't understand is that why the database can't detect it. I also have tried wrapping those variables with "" but still got no luck.
I am confused. I don't know how to fix this. The typical error, well you know it, I don't even think I have to post it. The mysqli_connect throws an error that no such host found even though the host was localhost. But when I try to plug in the actual parameters except for the 4th parameter it works.
connkey.txt contain these strings
localhost
root
password123
virtualassistant
print_r prints out the result
Array ( [0] => localhost
[1] => root
[2] => password123
[3] => virtualassistant
)
Am I missing something? Thanks for your time.