João Costa
João Costa

Reputation: 519

Using variables on select query table name

i need to use dynamic table names on model select query like this:

$this->db->select("$this->table_car.id as carId, $this->table_car.price as carPrice, $this->table_car.name as carName, $this->table_car.used as carUsed, $this->table_car.visible as carVisible, $this->table_cat.name as catName, $this->table_brand.name as carBrand, $this->table_model.name as carModel");

But variable is not working. This is what I get:

SELECT .`id` AS `carId`, .`price` AS `carPrice`, .`name` AS `carName`, .`used` AS `carUsed`, .`visible` AS `carVisible`, .`name` AS `catName`, .`name` AS `carBrand`, .`name` AS `carModel`
LEFT JOIN ON .`car_id` = .`id`
LEFT JOIN ON .`id` = .`cat_id`
LEFT JOIN ON .`id` = .`brand_model_id`
LEFT JOIN ON .`id` = .`model_id`
LEFT JOIN ON .`id` = .`brand_id`
WHERE .`used`= 0 LIMIT 3

Is there a workaround for this?

Thanks in advance

Upvotes: 0

Views: 80

Answers (1)

gabe3886
gabe3886

Reputation: 4265

Whilst double quotes do allow the use of variables inside them without the need to close and concatenate, it doesn't always work for the likes or object and arrays, like you are showing. A better solution would be:

$this->db->select($this->table_car . ".id as carId, " 
    . $this->table_car . ".price as carPrice, " 
    . $this->table_car . ".name as carName, " 
    . $this->table_car . ".used as carUsed, " 
    . $this->table_car . ".visible as carVisible, " 
    . $this->table_cat . ".name as catName, " 
    . $this->table_brand . ".name as carBrand, " 
    . $this->table_model . ".name as carModel");

Another option would be to put your object variables in braces {} such as :

$this->db->select("{$this->table_car}.id as carId, 
    {$this->table_car}.price as carPrice, 
    {$this->table_car}.name as carName, 
    {$this->table_car}.used as carUsed, 
    {$this->table_car}.visible as carVisible, 
    {$this->table_cat}.name as catName, 
    {$this->table_brand}.name as carBrand, 
    {$this->table_model}.name as carModel");

Upvotes: 1

Related Questions