Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP OOP MySQL Programming

Tags:

oop

sql

php

mysql

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?

like image 918
12japerk Avatar asked Jan 02 '12 23:01

12japerk


1 Answers

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.

like image 143
Charles Sprayberry Avatar answered Sep 21 '22 14:09

Charles Sprayberry