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.

8
  • 1
    check your $read array Commented Oct 3, 2013 at 6:49
  • I think you shouldn´t do your config this way! Have a look at this Question stackoverflow.com/questions/3996475/… Commented Oct 3, 2013 at 6: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. Commented Oct 3, 2013 at 6:57
  • 2
    @NeonWarge As you have posted your output, it clearly seen that the text is having 1 extra space, so use trim($localhost),etc.... Commented Oct 3, 2013 at 7:12
  • 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. Commented Oct 3, 2013 at 7:28

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

it works. So what must be the problem? Why is not working inside the loadKeyFromFile?
what you are getting if print_r($read); by not getting any data then there must be problem with file permission or data format.
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...:)

2 Comments

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
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
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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.