Pregunta

Hi all I need your advice on whether the following way of coding is acceptable and what better way to code in terms of 3 things, retrieving data, initializing variables and echoing it.

class Product {

private $product_name = array();
private $num_rows;

public function __construct() {
    include 'connect.php';
    $query = "SELECT * FROM product where product_status= 'open' ";
    $result = mysql_query($query);
    $this->num_rows = mysql_num_rows($result);
    while ($record = mysql_fetch_array($result)) {

        $this->product_name[] = $record['product_name'];
    }
}

public function get_rows() {
    return $this->num_rows;
}

public function get_name($count) {
    return $this->product_name[$count];
}

}

$product = new Product();
$rows = $product->get_rows();

for ($i = 0; $i < $rows; $i++) {

    echo $product->get_name($i);
}
¿Fue útil?

Solución

I don't like your class naming much. You call it a Product but it is in fact a ProductCollection or similar. In fact it is tied to a particular kind of ProductCollection an OpenProductCollection or OpenProducts if you prefer.

What if you wanted ClosedProducts or some other status as may have been set in product_status in your db?

$pc = new ProductsCollection('open');

Your use of 'SELECT * FROM product ...' when you only want name also seems wasteful, or would if each product had 100 fields .... we don't know how many fields you have.

So you might want to do the equivalent of:

$pc = new ProductsCollection;
$pc->set_fields(array('id', 'name'));
$pc->get_status_open();  // return your array

You could look at using magic __get and __set as another way to get round this, otherwise you could tightly tie your class to your table with get_name, get_price, get_manufacturer and so on.

Regarding the remarks about mysql_* functions if you move to either mysqli or PDO you can also SELECT into an OBJECT, so your result set could be an array of pre-filled Product objects. (ie a Product class you write which represents a single product).

HTH

Otros consejos

Only thing you have to worry about is the database handling. Try PDO rather than mysql_* functions. Follow this tutorial. That's all. Other than that everything else seems fine to me.

One last thing every-time you create $product = new Product(); database query will run. My question is it mandatory ? can you put it in a separate function. So that when you need it you can call it and get the data.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top