Displaying data of two tables on the same web page

2019-03-06 19:25发布

问题:

I am new to codeigniter. Currently I am working on a small project as practice and I am trying to display data of two tables on the same web page. I tried to use$this->db->join(); in codeigniter but it does not work for me. I was wondering is there other options that I can explore of displaying two table data on a same web page?

I am also posting my join method that I have tried - maybe you can tell me I did something wrong?

model

  $this->db->select('tblanswers.*,credentials.*');
    $this->db->from('tblanswers');
    $this->db->join('credentials', 'tblanswers.answerid = credentials.cid', 'left'); 
    $query = $this->db->get();
    return $query->result();

The problem with this join function I have that it only displays one table but not the other. I used the print_r($data['query']); die() to checked this it only returns the tblanswer not both.

EDIT

Table structure:

credentials

+--------------+------+-------------+-------+-------+
| cid(PRIMARY) | name | second_name | phone | email |
+--------------+------+-------------+-------+-------+

tblanswers

+-------------------+--------+------------+---------+---------+---------+
| answerid(PRIMARY) | userid | questionid | answerA | answerB | answerC |
+-------------------+--------+------------+---------+---------+---------+

回答1:

ok so first of all your table MUST have relational data to perform a join

return $this->db->select('tblanswers.*,credentials.*')
                      ->join('credentials cred', 'tblanswers.answerid = credentials.cid', 'LEFT')
                      ->get('tblanswers')
                      ->result_object()

so this will perform a query fetching the data from the credentials table where the *answerid field = the cid field

E.G

  SELECT * FROM tblanswers
  JOIN credentials ON credentials.cid = tblanswers.answerid

EDIT

seems like you dont event need to use a join for what you want you could simply go

 return $this->db->select('tblanswers.*,credentials.*')
                ->from('tblanswers, credentials')
                ->get()
                ->result_object();

because it doesnt seem like you have any relational data between the two but for example you could get all questions relating to that awnser by going

return $this->db->select('tblanswers.*,questions.*')
                      ->join('questions AS q', 'tblanswers.questionid = q.question_id', 'LEFT')
                      ->get('tblanswers')
                      ->result_object()