F0313
F0313

Reputation: 31

PHP and Mysql Object oriented

I only see "connected" on my screen and nothing else. How can I show the mysql table rows on the screen?

<?php
class db {
    private $conn;
    private $host;
    private $user;
    private $password;
    private $baseName;
    private $port;

    function __construct($params=array()) {
        $this->conn = false;
        $this->host = 'localhost'; //hostname
        $this->user = 'fp0313'; //username
        $this->password = ''; //password
        $this->baseName = 'test'; //name of your database
        $this->port = '3306';
        $this->connect();
    }

    function __destruct() {
        $this->disconnect();
    }

    function connect() {
        if (!$this->conn) {
            $this->conn = mysql_connect($this->host, $this->user, $this->password); 
            mysql_select_db($this->baseName, $this->conn); 

            if (!$this->conn) {
                $this->status_fatal = true;
                echo 'Connection BDD failed';
                die();
            } 
            else {
                $this->status_fatal = false;
                echo 'Connected';
            }
        }

        return $this->conn;
    }

        function selectData()
    {
        $User = $bdd->getOne('SELECT stud_id, stud_voornaam, stud_achternaam FROM student'); // 1 line selection, return 1 line
        echo $User['stud_id'].'<br>'; // display the id
        echo $User['stud_voornaam'].'<br>'; // display the first name
        echo $User['stud_achternaam']; // display the last name
    }


    function disconnect() {
        if ($this->conn) {
            @pg_close($this->conn);
        }
    }
}
$bdd = new db(); // create a new object, class db()
?>

Upvotes: 1

Views: 1644

Answers (5)

Anwar Hussain
Anwar Hussain

Reputation: 13

// Add this 2nd line

$bdd = new db();
$bdd->selectData();

Upvotes: 0

M. Salman Khan
M. Salman Khan

Reputation: 616

It seems like you don't really understand how PHP classes work, so I'll walk you through the basics of OOP PHP. A full answer would be too long to post as an answer, so I've just put a brief introduction, and links to more detailed explanations :)

Properties

Properties are essentially variables associated with an instance of an object. There can also be static properties, which are associated with a class. Properties can be declared as public, private or protected. Read more....

Methods

Similar to properties in that they are associated with instances of classes or of the class itself, methods are just functions which are part of a class. Methods can also be static, and can also be declared public, private or protected. The same link as above applies to this.

Magic Methods

PHP has some 'Magic methods'. These are just names for methods that are reserved for special functionality. For example, the __construct is a magic method, which is run when the object is initialized. __clone is also a magic method, which is run when the object is cloned. To define one of these, you simply define a method with the same name as the magic method, and that method will be run at specific points, eg for the __construct; when the object is created, for the __clone method, it will be run when the object is cloned. Also, just a note — you don't need to define all magic methods, you only need to define the ones that you wish to be used. Read more...

Other links relating to important parts of OOP PHP, which are less relevant to your situation, but that are still important to know

In Context

So now you understand the basics behind OOP PHP, lets dig into what the class you've provided in your question does!

First lets look at this part:

private $conn;
private $host;
private $user;
private $password;
private $baseName;
private $port;

This declares all the properties. The private means that these properties will be available only from this class, and not any extending classes (See above link on extending classes).

Now lets look at this:

function __construct($params=array()) {
    $this->conn = false;
    $this->host = 'localhost'; //hostname
    $this->user = 'fp0313'; //username
    $this->password = ''; //password
    $this->baseName = 'test'; //name of your database
    $this->port = '3306';
    $this->connect();
}

This does not take any parameters. You can pass in a parameter, but that will not be used, and if you pass in nothing, an empty array will be assigned to the variable $params, which has only a local scope, as it is part of a function.

As you now know, this function will be executed when the object is created, so this assigns values to some of the properties; it sets $conn to false, $host to 'localhost', ect. It then runs the connect() function (you can skip to that bit to see what that does)

Now let's look at this: function __destruct() { $this->disconnect(); } This defines the __destruct magic method, which is run when the object is destroyed, which usually occurs at the end of a script. In this case, the function simply runs the disconnect() function, which we'll get to later.

Now this part:

function connect() {
    if (!$this->conn) {
        $this->conn = mysql_connect($this->host, $this->user, $this->password); 
        mysql_select_db($this->baseName, $this->conn); 

        if (!$this->conn) {
            $this->status_fatal = true;
            echo 'Connection BDD failed';
            die();
        } 
        else {
            $this->status_fatal = false;
            echo 'Connected';
        }
    }

    return $this->conn;
}

This first checks to see if $conn is set to false (It uses the ! (not) operator to reverse it, so the condition evaluates as true if the inverse of $conn is true.). If this is the case, there is no database connection yet, so it creates one using mysql_connect(), and assigns the connection to the $conn property. It then selects the database. It then checks to ensure that the connection was successful. If it was not, the $status_fatal property is set to true, "Connection BDD failed" is echoed, and the execution is stopped using die, and if the connection was successful, the $status_fatal property is set to false, and the word 'Connected' is echoed. This is what you are seeing at the moment. The function then returns the $conn property.

As someone pointed out in the comments of your question, you may want to select the database after you establish that the connection was successful, as this means that you will not be trying to select a database when the connection failed.

Now let's look at this part:

    function selectData()
{
    $User = $bdd->getOne('SELECT stud_id, stud_voornaam, stud_achternaam FROM student'); // 1 line selection, return 1 line
    echo $User['stud_id'].'<br>'; // display the id
    echo $User['stud_voornaam'].'<br>'; // display the first name
    echo $User['stud_achternaam']; // display the last name
}

There is actually an error with this method. Since this is in a function, all variables have local scope, and to target class properties, you need to refer to $this. So when you use $bdd, it assumes that within that local scope, there is such a variable, so you need to pass that in as a parameter to the function.

Assuming that you have now fixed that error, and passed in an object as a parameter, that object's method GetOneis run. I cannot tell you what this does, because I do now know what the $dbb object contains. It's kind of difficult to explain what happens without knowing, so I guess I'll rewrite something similar, without that object. You should be able to figure out how to adapt this to your situation. Here is how it would work using a mysql query (Note: I'm using mysqli, which is what you should be using, as mysql_* functions are now depreciated.):

function SelectData() {
    $result = mysqli_query($this->conn, "SELECT stud_id, stud_voornaam, stud_achternaam FROM student LIMIT 1");
    $user = mysqli_fetch_assoc($result);

    echo $user['stud_id'] . "<br />\r\n";
    echo $user['stud_voornaam'] . "<br />\r\n";
    echo $user['stud_achternaam'];
}

This references the connection previously made, in the mysqli_query() method, which queries the database. The results are then stored in the $result variable. mysqli_fetch_assoc() is then used to convert that result set into an associative array, which is then echoed. The function in your object probably does something similar to this.

Now let's look at this part:

function disconnect() {
    if ($this->conn) {
        @pg_close($this->conn);
    }
}

This closes a database connection. I believe this to be an error, however, as you have previously created a mysql database connection, but the pg_close() is for postgreSQL. I believe what you wanted was mysql_close().

"Okay... but I'm still getting the same result"

When you create your object using $bdd = new db(), the constructor is called, which as we established before, calls the connect method, which echoes "connected" when a connection is established, so this well be echoed. But to display the results, you need to call the selectData() method, which you do using the -> operator, like this $bdd->selectData().


I tried explaining everything in a lot of detail, but if you don't understand something, feel free to ask for clarification.

Upvotes: 4

devlin carnate
devlin carnate

Reputation: 8592

Your constructor calls this->connect, which is why you get the "connected" message. However, you never call selectData().

$bdd = new db(); // create a new object, class db()
$bdd->selectData();

You will also want to call $bdd->disconnect();

Upvotes: 0

Edu C.
Edu C.

Reputation: 408

You are only getting the 'Connected' because you only created the object.

Using $bdd->selectData(); will return the data you want.

Upvotes: 0

Roman
Roman

Reputation: 2549

You are just creating a new db-object with $bdd = new db() and as your code mentions you are echoing Connected if you are connected. If you want to do something, you have to run $bdd->selectData() for example.

Upvotes: 0

Related Questions