[eluser]Mortaned[/eluser]
Hi, everyone. I've been programming in PHP + MySQL for a few months now and I have to say that CI has been my best find so far. Two thumbs up.
I have a Cars table with the following data:
--------------------------------------
brand - modl - color
--------------------------------------
Ferrari - F40 - Red
Ferrari - Testarosa - Yellow
Porsche - 911 - Black
Porsche - 911 Carrera - Black
Lamborghini - Diablo - Yello
--------------------------------------
and so on.
And what I want to do is a set of independent tables that use the brand as an external header, like this:
Ferrari:
<table with Ferrari models>
Porsche:
<table with Porsche models>
etcetera.
Now, I managed to make it work using the following code:
class Cars_m extends Model
{
function getBrands()
{
$query = $this->db->query("SELECT DISTINCT brand FROM cars ORDER BY brand");
return $query->result_array();
}
function getModels($cars)
{
$query = $this->db->query("SELECT * FROM cars WHERE brand = '$cars' ORDER BY modl ASC");
return $query->result_array();
}
}
class Cars_c extends Controller
{
function __construct()
{
parent::Controller();
$this->load->model('Cars_m');
}
function index()
{
$vars['cars'] = $this->getCars();
$this->load->view('Cars_v',$vars);
}
function get_Cars()
{
$table = "";
$brands = $this->Cars_m->getBrands();
foreach($brands as $brand)
{
echo "<h1>".$brand['brand']."</h1>";
$table .= "<table>";
$models = $this->Cars_m->getModels($brand['brand']);
foreach($models as $model)
{
$table .= "<tr><td>".$model['modl']."</td><td>".$model['color']."</td></tr>";
}
$table .= "</table>";
}
return $tabla;
}
}
Cars_v calls the variable like this:
<div class="car_brands">
<?php echo $cars; ?>
</div>
As I said before, this is working just fine, but I have three topics on which I wanted to ask for advice:
1. I'm concerned about calling the getModels function inside the first foreach. I think that if the cars database becomes very large, this could eventualy be an issue for I am performing a query for every brand in my table. Is there a way to avoid this?
2. I'm not realy sure about the way I'm concatenating the tables. This is how I would do it using plain PHP, buy I'm sure CI offers a better way to treat this.
3. I tried to solve the previous point using the table class getting this code in the getCars funtion (adding a header for each table):
$brands = $this->Cars_m->getBrands();
foreach($brands as $brand)
{
echo "<h1>".$brand['brand']."</h1>";
$this->table->set_heading('Model','Color');
$models = $this->Cars_m->getModels($brand['brand']);
foreach($models as $model)
{
$this->table->add_row($model['model'],$model['color']);
}
$this->table->generate();
$this->table->clear();
}
But it doesn't display a thing. Why could that be?
I realy appreciate your help.