user3057514
user3057514

Reputation: 261

passing variables between classes and database function

I am just getting into OOP and I am trying to do everything as correct as possible and in the right way.

I have a Product class with 2 methods RetrieveFromDatabase and Display RetrieveFromDatabase access one argument which the product ID and it basically runs a PDO statements which I wrote in my abstract class(dont know if this is the right as PDO already have some of this functions already). It using this ID to fetch the product details.

Display the idea of this function is to render the product details. In this example I only have 1 html but I was planning to add a lot more as I do not know how to pass each of them to a div, which is not in function(normally i do(<div> <?php echo $name; ?> </div>) before I heard about OOP.

Class Product {

    public $name;   
    public $price;
    public $length;
    public $description;
    public $type;
    private $results;
    private $database_connection

    private function __construct(Database $database_connection) {
        // database connection
        $this->database = dbconnect(); 
    }

    public function RetrieveFromDatabase($id) {
         $sql->database_connection->query('select Name, price, length, description FROM product WHERE id = :id');
         $sql->database_connection->bind(':id', $id);
         $sql->database_connection->execute();

         return $this->results !== false;
        //Retrieve the product details from database.
    }

    public function Display() {
    //display the product information
      while(($row = mysql_fetch_row($this->results)))
       print_r($row);
    echo <p> $this->database_connection->price </p>;
    }

    $Product = New Product();
}

My Question

How can I write the above code in the proper way without having to include any html in the class file? And also please correct me if I have made any stupid mistakes.

Upvotes: 0

Views: 86

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157828

Refrain from trying OOP for a while.

In fact, you made everything as incorrect as possible and in the wrong way.

Not to mention you still have quite vague idea on the API you are using. So, better stick to old good procedural style, until you grasp PHP basics and learn some OOP from various sources.

Update. Do not try to create classes of your own but learn from ready-made ones. Take yourself a framework, which all the learned developers already inclined to, and which will teach you proper OOP approaches by example. Yii and Laravel looks most promising ones.

Upvotes: 3

Related Questions