HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Am I on the right track? PHP/MySQL

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thetrackphpmysqlright

Problem

I have the following table called info:

info_name   |   info_value

name        |   Susan

desc        |   Human


I'm trying to print Susan without knowing that the value is Susan.

The following code works, but I want to know if what I wrote is correct.

I'm open to any improvements.

Config Class:

class Config {

    private $hostname = 'localhost';
    private $username = 'blah';
    private $password = 'blah';
    private $database = 'blah';

    public function __construct()
    {
        $this->connection = new mysqli($this->hostname,$this->username,$this->password,$this->database);

        if($this->connection->connect_errno) 
        {
            die('Error: ' . $this->database->error);
        }
    }

    public function query($query)
    {
        return $this->connection->query($query);
    }

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

}


Name Class:

class Name {

    protected $name;

    public function __construct()
    {
        $this->db = new Config;

        $r = $this->db->query('SELECT info_value FROM info WHERE info_name="name"');

        while($row = $r->fetch_row())
        {
            $this->name = $row['0'];
        }

    }

    public function getName()
    {
        return $this->name;
    }

}


Print Results:

getName(); ?>


Thanks for any help!

Solution

Your config and name classes are good starts. Here are a few humble suggestions:

-
I highly suggest steering clear of what is called the entity-attribute-value pattern when structuring your MySQL tables. Here is an article that discusses ways of refactoring. Also, if you are interested in learning more about mysql (and sql in general) I highly recommend the book SQL Antipatterns by Bill Karwin.

-
In the future, if your projects grow and you want a more robust system, you may want to look into a few concepts such as dependency injection, which will help if and (hopefully) when you ever start unit testing with software like PHPUnit.

Hope this helps!

Context

StackExchange Code Review Q#10418, answer score: 3

Revisions (0)

No revisions yet.