can sombody give me a great example to make a connection php - mysql ( oop - best practice ) ?

<?php 
/* Database Connection */
class db
{
private $db['host']='localhost';
private $db['user']='root';
private $db['pass']='';
private $db['name']='build';
public function connect($db['host'],$db['user'],$db['pass'])
{
$db['connect'] = mysql_connect($db['host'],$db['user'],$db['pass']);
if (!$db['connect']) {
	printf("Cannot connect to database: %s\n", mysql_error())
}
else
	{
	echo "Connected";
}
// end funtion
}
// end class
}
?>

i dont know what cause this error above ( mycode )
sry newbie

Hi.

Sure, I can give you an example.
It's pretty basic at this point, but I assume you are going to be adding your own methods to it.

Note that I don't store the actual password used for the connection, but rather a SHA1 has of it. (For security reasons)
And I don't allow the outside code to alter the stored database connection information. (No reason to allow that, really)

Also note that I use the constructor to connect to the database.
If you want the class to support reusing an instance for multiple connections, you will need to create open() and close() methods.

<?php
class MySQL_Database
{
    /** The database link,.
     * Used by the code to execute queries and such **/
    private $dbLink;

    /** Connection property values **/
    private $host; // Host name. E.g. "localhost"
    private $user; // Name of the MySQL user
    private $dbName; // Name of the database to use
    private $password; // A hash of the user's password

    /**
     * The constructor.
     * Establishes a connection to the database.
     * @param string $host
     * @param string $user
     * @param string $password
     * @param string $dbName
     */
    public function __construct($host, $user, $password, $dbName)
    {
        // Connect
        $this->dbLink = mysql_connect($host, $user, $password);
        if(!$this->dbLink) {
            throw new Exception("Connection to database failed.");
        }
        if(!mysql_select_db($dbName)) {
            throw new Exception("Failed to set the database.");
        }

        // Set getter values.
        $this->host = $host;
        $this->user = $user;
        $this->dbName = $dbName;

        // Create a hash of the password and store it.
        // Never store passwords as plain text... it's
        // pointless and extremely insecure.
        $this->password = sha1($password);
    }

    /***
     * The destructor. (Called when the object is destroyed.)
     * Closes the dbLink if needed.
     */
    public function  __destruct() {
        @mysql_close($this->dbLink);
    }

    /*
     * The following are the getters, to allow outside access
     * to the connection properties.
     */
    public function getHost() {
        return $this->host;
    }
    public function getUsername() {
        return $this->user;
    }
    public function getPasswordHash() {
        return $this->password;
    }
    public function getDatbaseName() {
        return $this->dbName;
    }

    /*
     * And here you would define functions to interact with your
     * database, like a method to execute queries.
     */

    /**
     * Executes a query.
     * @param <type> $sql The SQL query to be executed
     * @return resource The MySQL resource returned by the query.
     */
    public function query($sql) {
        if(!$sql) {
            throw new Exception("Query is invalid.");
        }

        $result = @mysql_query($sql, $this->dbLink);
        if($result) {
            return $result;
        }
        else {
            throw new Exception("Query failed: ". mysql_error($this->dbLink));
        }
    }
}
?>

And here is how you would use that:

<?php
try {
    $db = new MySQL_Database("localhost", "usr", "passwd", "test");
    $result = $db->query("SELECT something FROM somethingElse");

    while($row = mysql_fetch_assoc($result)) {
        print_r($row);
    }
}
catch(Exception $ex) {
    printf("Datbase execution failed: %s", $ex->getMessage());
}
?>

Hope that helps.

Hi.

Sure, I can give you an example.
It's pretty basic at this point, but I assume you are going to be adding your own methods to it.

Note that I don't store the actual password used for the connection, but rather a SHA1 has of it. (For security reasons)
And I don't allow the outside code to alter the stored database connection information. (No reason to allow that, really)

Also note that I use the constructor to connect to the database.
If you want the class to support reusing an instance for multiple connections, you will need to create open() and close() methods.

<?php
class MySQL_Database
{
    /** The database link,.
     * Used by the code to execute queries and such **/
    private $dbLink;

    /** Connection property values **/
    private $host; // Host name. E.g. "localhost"
    private $user; // Name of the MySQL user
    private $dbName; // Name of the database to use
    private $password; // A hash of the user's password

    /**
     * The constructor.
     * Establishes a connection to the database.
     * @param string $host
     * @param string $user
     * @param string $password
     * @param string $dbName
     */
    public function __construct($host, $user, $password, $dbName)
    {
        // Connect
        $this->dbLink = mysql_connect($host, $user, $password);
        if(!$this->dbLink) {
            throw new Exception("Connection to database failed.");
        }
        if(!mysql_select_db($dbName)) {
            throw new Exception("Failed to set the database.");
        }

        // Set getter values.
        $this->host = $host;
        $this->user = $user;
        $this->dbName = $dbName;

        // Create a hash of the password and store it.
        // Never store passwords as plain text... it's
        // pointless and extremely insecure.
        $this->password = sha1($password);
    }

    /***
     * The destructor. (Called when the object is destroyed.)
     * Closes the dbLink if needed.
     */
    public function  __destruct() {
        @mysql_close($this->dbLink);
    }

    /*
     * The following are the getters, to allow outside access
     * to the connection properties.
     */
    public function getHost() {
        return $this->host;
    }
    public function getUsername() {
        return $this->user;
    }
    public function getPasswordHash() {
        return $this->password;
    }
    public function getDatbaseName() {
        return $this->dbName;
    }

    /*
     * And here you would define functions to interact with your
     * database, like a method to execute queries.
     */

    /**
     * Executes a query.
     * @param <type> $sql The SQL query to be executed
     * @return resource The MySQL resource returned by the query.
     */
    public function query($sql) {
        if(!$sql) {
            throw new Exception("Query is invalid.");
        }

        $result = @mysql_query($sql, $this->dbLink);
        if($result) {
            return $result;
        }
        else {
            throw new Exception("Query failed: ". mysql_error($this->dbLink));
        }
    }
}
?>

And here is how you would use that:

<?php
try {
    $db = new MySQL_Database("localhost", "usr", "passwd", "test");
    $result = $db->query("SELECT something FROM somethingElse");

    while($row = mysql_fetch_assoc($result)) {
        print_r($row);
    }
}
catch(Exception $ex) {
    printf("Datbase execution failed: %s", $ex->getMessage());
}
?>

Hope that helps.

It's really just my opinion but I prefer Database classes to be static classes which wrap a Database Connection singleton. The Database class should really never connect to the database to preserve separation of concern

thanks
but , there is a few things that i cant understand

$this->host = $host;
$this->user = $user;
$this->dbName = $dbName;

what does $this and "->" do ? and where is the
content or sustention of $host ? and $user, $host, $dbname ?
like this

// so var db['host'] has a content or substention that is "localhost"
$db['host']='localhost';

__construct and __destruct() ?

and last one is

public function getHost() {
return $this->host;
}

is it the same as

public function getHost(thesubstention) {
return $this->thesubstention;
}

thanks for your replays , may god replay :)

It's really just my opinion but I prefer Database classes to be static classes which wrap a Database Connection singleton. The Database class should really never connect to the database to preserve separation of concern

True, and this is what I usually do as well.
I just though I'd offer a more basic example first before diving into advanced topics like static methods and singletons :)

Although, in tier-3 and MVC frameworks, you can usually get away with using an instanced DB abstractation layer like that.
They usually have a central access point for database interaction, which doesn't really require more than a single instance.

thanks
but , there is a few things that i cant understand

$this->host = $host;
$this->user = $user;
$this->dbName = $dbName;

what does $this and "->" do ? and where is the
content or sustention of $host ? and $user, $host, $dbname ?
like this

// so var db['host'] has a content or substention that is "localhost"
$db['host']='localhost';

In PHP OOP, class functions and variables are accessed using the arrow -> .
When coding inside class functions, you can use the $this variable to access the class itself.

Maybe this will help explain:

class foo {
  // This is a class variable.
  // It can be used by the functions inside the class by using the
  // $this variable. Like $this->variable
  private $variable;
  
  // This is a simple function to set the value of the variable
  // The $newValue is parameter. It is set by whatever code
  // calls the function, and the value is passed into it.
  public function setVariable($newValue) {
    // This simply sets the variable, using the $this keyword.
    // It sets it to the value passed via the parameter of the function.
    $this->variable = $newValue;
  }

  // Also a function. It simply prints the variable.
  function printVariable() {
    echo $this->variable;
  }
}

// This creates a new instance of the class.
$inst = new foo();

// This sets the variable inside the class using the 
// function I created. It passes a value via the parameter
// which the function will use to set the variable.
$inst->setVariable("Hello");

// This simply calls the function that prints the variable.
$inst->printVariable(); // Prints: Hello

__construct and __destruct() ?

The __construct function of a class is called when it is created. It is typically used to initialize class variables.
The __destruct function is called when the class is destroyed. It is typically used to close resources used by the class.

See Constructors and Destructors in the manual for a better explanation.

and last one is

public function getHost() {
return $this->host;
}

is it the same as

public function getHost(thesubstention) {
return $this->thesubstention;
}

No. The first one returns a class variable, using the $this keyword.

The second one (overlooking the syntax error in the parameter), would have taken in a parameter named $thesubtention , but returned a class variable named $thesubtention .

The two are not the same. When you use $this->variable inside a class function, it is referring to a variable outside the function itself, belonging to the class.
(See Variable Scope in the manual for a detailed explanation.)


You should really check out the manual entry Shawn posted, or maybe an OOP tutorial. It's probably quicker, and better explained, than this :)

no this is the best . really thanks atli .

Be a part of the DaniWeb community

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