Search code examples
mysqlescapingcodeigniter-2

Codeigniter:Using defined constants for table names in a join call


I have a defined constant for each of my database tables.

define('QTABLE','questions');
define('ATABLE','answers');

I would like to join these tables using a commonly referenced column "xid".

Here's how I'd do it if I referenced the actual name of the tables.

$this->db->from('questions');
$this->db->select('qcount,answers.xid,answers.aval');
$this->db->join('answers','questions.xid=answers.xid');
$gquery=$this->db->get();

But I do not want to reference the table names directly in the code in case we need to rename them later. How would I use the defined constants correctly to do this with Codeigniter's Active Records? I suspect it's all about escaping with the correct kind of single/double quotes.

I tried the following and it definitely does not work!

$this->db->from(Q-TABLE);
$this->db->select('qcount,ATABLE.xid,ATABLE.aval'); <----PROBLEM
$this->db->join(ATABLE,'QTABLE.xid=ATABLE.xid');<------PROBLEM
$gquery=$this->db->get();

Could you show me the way to the light?

mmiz


Solution

  • In your model

    function __construct()
    {
        // Initialization of class
        parent::__construct();
        define('QTABLE','questions'); // define constant here in constructor
        define('ATABLE','answers');  // define constant here in constructor
    }
    

    try query like this

    $this->db->select('qcount,'.ATABLE.'.xid,'.ATABLE.'.aval'); 
    $this->db->from(QTABLE);
    $this->db->join(ATABLE,QTABLE.'.xid='.ATABLE.'.xid');
    $query=$this->db->get();
    echo $this->db->last_query(); exit;