0

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.

Neon Warge
  • 1,817
  • 6
  • 29
  • 53
  • 1
    check your $read array – Rohit Choudhary Oct 03 '13 at 06:49
  • I think you shouldn´t do your config this way! Have a look at this Question http://stackoverflow.com/questions/3996475/creating-configuration-file-in-php – makim Oct 03 '13 at 06:51
  • Hmm I don't understand what config my code will be? Actually it just read a simple text file, where the name of localhost username password and database is written that is all there is to that. I just can't understand why $localhost, $username ,$password fails as if it reads a garbage letters while database is not? Yeah I'll to dump the contents of the array and see what fails. I somehow can sense that might be the problem because $db is the last to be read from file. I do it this way so that I could learn how PHP classes works, it just happens that I tried it on db connection. – Neon Warge Oct 03 '13 at 06:57
  • alright so var_dump says: array(4) { [0]=> string(11) "localhost " [1]=> string(6) "root " [2]=> string(13) "password123 " [3]=> string(16) "virtualassistant" } – Neon Warge Oct 03 '13 at 07:00
  • 2
    @NeonWarge As you have posted your output, it clearly seen that the text is having 1 extra space, so use `trim($localhost),etc...`. – Yogesh Suthar Oct 03 '13 at 07:12
  • damn it seems to be the problem! wait a sec let me edit once again, I post the result of print_r. – Neon Warge Oct 03 '13 at 07:22
  • Hello yeah there is really something wrong in there. I've re-wrote the text file so there you have it still the same. I just have a theory. As you can notice I have separated each by line so how can I remove the '\n' thingy? I thought it wasn't being read after all. I just wanted to know if there is a function in PHP that just the text line by line without adding that additional new line?? I'll search about it. – Neon Warge Oct 03 '13 at 07:26
  • 1
    Great it works! So I don't like trimming while reading, is there a way to read each line by line without including the extra '\n'. In my code it reads that new line as a space. Weird. – Neon Warge Oct 03 '13 at 07:28

3 Answers3

2

write as below

$con = new Connection();
$con->connect('localhost','username','password','database_name');

try to echo in connect function whether you are getting these passed variable values or not. These should work for you. As well set value to true for variable $_isConnected in connect function if successfully connected.

  • it works. So what must be the problem? Why is not working inside the loadKeyFromFile? – Neon Warge Oct 03 '13 at 07:12
  • 1
    what you are getting if print_r($read); by not getting any data then there must be problem with file permission or data format. –  Oct 03 '13 at 07:16
1

I think, you failed to read the configuration file properly. the following link describe various ways to read data from configuration file.

http://www.phpro.org/articles/Application-Configuration.html

For example:

create a file called "config.ini" or whatever.

put the following content to the file:

[database]
db_username = virtualassistant
db_password = password123
db_host = localhost
db_name = test

Now, from your PHP script:

<?php

/*** parse the ini file ***/
    $config = parse_ini_file("config.ini", 1);

    /*** print the array ***/
    print_r($config);

You will receive an array like the following:

Array
    (
        [database] => Array
        (
            [db_username] => virtualassistant
            [db_password] => password123
            [db_host] => localhost
            [db_name] => test
        )
)

Simple...:)

Anam
  • 11,999
  • 9
  • 49
  • 63
  • Woah big word, I dont have config file similar to that. My text file contains simple text namely: localhost root password123 virtualassistant That's it so simple – Neon Warge Oct 03 '13 at 07:02
  • Wow thanks! It is a nice idea on how to write a connection class properly but actually the way I read my text file is simple. I hope you have read my post. I've edited it. I don't want to try that one just yet. I can't get over this one. lol – Neon Warge Oct 03 '13 at 07:16
0

So according to Yogesh Suthar, he notices that there is an extra space with each parameter except the fourth. This is because I read this text file line by line such that each parameter are separated by newlines so when I read that line it translates that newline into a space I said this because of the result of my var_dump. I may be wrong by that statement but that causes the problem. The fourth parameter is no longer separated because the next is already the EOF so it doesn't have an extra space. I haven't suspected that. So for now I have tried to trim using trim( $val ) each parameters as suggested and it works! Thank you guys! You are so awesome!

Neon Warge
  • 1,817
  • 6
  • 29
  • 53