7

I am a beginner in PHP programming and would like help with a little question. Please take a look at the code below:


PHP Code

<?php
class Account
{
  public function register()
  {
    $db_link = mysql_connect("localhost","root","");  // Create Connection
    if (!$db_link)  // Check connection
    {
      die(mysql_error());
    }

    mysql_close($db_link); // Close Connection
  }

  public function login()
  {
    $con = mysql_connect("localhost","root","")  // create connection
    if (!$con)  // create connection
    {
      die(mysql_error());
    }
    mysql_close($con); //close connection
  }

}
?>

My question is if creating individual db links for every single one of the object's methods is the best way to go? Is there a better or alternative way to do this? Hopefully I've explained well enough.


Would the following be correct?

$x = new Account("localhost", "root", "");

-and x would have its own connection...and then close when its done?

5
  • 2
    Just use mysql_connect() and mysql_close() at the beginning and at the end of your whole program. There is no need to instantiate a connection at every method. Commented Jan 2, 2012 at 23:20
  • @ldiqual: your comment could be an answer! Commented Jan 2, 2012 at 23:23
  • 4
    @idiqual You should not be encouraging the use of mysql_ at all, particularly for somebody just coming into the language and is starting a new project. Commented Jan 2, 2012 at 23:23
  • 1
    if you want to keep db to the Accounting class connect in your __construct and implement __destruct method to destroy connection when object is destroyed. Commented Jan 2, 2012 at 23:24
  • Use singleton pattern. Example stackoverflow.com/questions/8685896/… Commented Jan 2, 2012 at 23:33

5 Answers 5

10

I would not advise creating your database connections this way. Create one connection and inject that into the object using it. You should not need to create a new connection for every object.

Code example:

$connection = new mysqli('localhost', 'user', 'password');

$Account = new Account($connection);

Would need to change Account to look like:

class Account {

    protected $connection;

    public function __construct(mysqli $connection) {
        $this->connection = $connection;
    }

    public function register() {
        // use $this->connection for db
    }

    public function login() {
        // use $this->connection for db
    }

}

I would also suggest that you take a look at the php.net docs about choosing a MySQL API. If you really want to use OOP with PHP and MySQL you will need to swap over to mysqli or PDO as the API you are using does not truly support an OOP interface.

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

2 Comments

You forgot to close the connection.
@GabrielSantos No, I didn't close it on purpose. What if there's another object that needs to use that connection? Then we have to open the connection again. The code that created the connection object should be responsible for closing the connection.
3

I suggest:

public function __construct(mysqli $connection) {
    $this->connection = $connection;
    if(!$this->$connection) {
        die(mysql_error());
    }
}

public function __destruct() {
    mysql_close($this->$connection);
}

7 Comments

I'm not sure I'd recommend using die in this (or any OO) situation.
@cbuckley It is only for sample purpose.
My only concern was that it might be a bad example to set to a beginner PHP programmer, OOP or otherwise.
No, is not. die have not relation to OOP.
Exception handling is an integral part of OOP. die() immediately produces fatal errors. See stackoverflow.com/questions/3845494/php-oop-exceptions-or-die
|
0

You can use some codes like as:

$db_link = mysql_connect("localhost","root","");  // Create Connection
if (!$db_link)  // Check connection 
{
  die(mysql_error());
}
mysql_select_db("db_name");
$q=mysql_query("SELECET * FROM table_name LIMIT 1");

Other queries would be here

mysql_close($db_link); // Close Connection

Creating single connection at each page is enough. more than one connection or disconnecting from sql server and loginning again may cause reduced performance.

Comments

-1

You can use a static member and all your objects will share one database connection.

See also PHP - a DB abstraction layer use static class vs singleton object?

3 Comments

I wouldn't use neither (static class or singleton).
Downvote for singleton. No reason to introduce a database connection into the global scope with static
@CharlesSprayberry Agree again.
-1

If you wanted to shrink it and keep it neater/more manageable you could put the mysql connect code into it's own method and call it like so:

<?php
class Account
{
  private $connection;

  private function connect()
  {
    $this->$connection = mysql_connect("localhost","root","");  // Create Connection
  }

  public function register()
  {
    $this->connect();
    if (!$this->$connection)  // Check connection
    {
      die(mysql_error());
    }

    mysql_close($this->$connection); // Close Connection
  }

  public function login()
  {
    $this->connect();
    if (!$this->$connection)  // create connection
    {
      die(mysql_error());
    }
    mysql_close($this->$connection); //close connection
  }

}
?>

3 Comments

Downvoted because ultimately you're still creating the database connection every time a function is called.
@CharlesSprayberry Agree with you.
@CharlesSprayberry I misinterpreted the original question

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.