I would like some help with my connect class.This class is created by me it is my way of thinking so i would like to know why this class dossent get my variables and connect proprely to mysql.

the code

<?php /**
*

Exp:Connect to database in oop style

@params host dbname username password


*/

class Connect  
{
    //private only available forthe current class
    private $host=null;

    private $dbname = null;

    private $username = null;

    private $password = null;


    function __construct($host,$dbname,$username,$password)
    {

        $this->host = $host;

        $this->dbname = $dbname;

        $this->username = $username;

        $this->password = $password;

        $host = "localhost";
        $dbname = "testoop";
        $username = "root";
        $password = "";



    }



    function connect(){

    try {

    $conn = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname, $this->username, $this->password);

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch(PDOException $e) {

    echo 'Unable to connect';
    }

    }
} 

$con = new Connect();

$con->connect();




?>

Thank you for your time and any advices regarding security

Recommended Answers

Lines 34-37 don't belong there, remove them. What you should do is change line 61 to:

$con = new Connect('localhost', 'testoop', 'root', '');
Jump to Post

Personally I wouldn't, but it's your choice. You can do this:

function __construct()
{
    $this->host = "localhost";
    $this->dbname = "testoop";
    $this->username = "root";
    $this->password = "";
}
Jump to Post

All 6 Replies

Re: Php oop connect pdo 80 80

Lines 34-37 don't belong there, remove them. What you should do is change line 61 to:

$con = new Connect('localhost', 'testoop', 'root', '');
Re: Php oop connect pdo 80 80

I would like to get the db connect values form the constructor or this is considered a bad practice?

Re: Php oop connect pdo 80 80

Personally I wouldn't, but it's your choice. You can do this:

function __construct()
{
    $this->host = "localhost";
    $this->dbname = "testoop";
    $this->username = "root";
    $this->password = "";
}
Re: Php oop connect pdo 80 80

Why would you not do this?

Is there any secuirty or performance issues involved?

Re: Php oop connect pdo 80 80

Ok thank you for you time this thread is solved

Re: Php oop connect pdo 80 80

Is there any secuirty or performance issues involved?

No. It's just that it's easier to reuse that class if it doesn't contain the connection information hard-coded.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.