CodeIgniter/PHP/MySQL: Retrieving data with JOIN

前端 未结 4 1937
失恋的感觉
失恋的感觉 2020-12-14 05:10

I\'m new to PHP/MySQL and super-new to CodeIgniter.. I have information in many MySQL tables. I want to retrieve it with JOIN where the tables primary keys are equal to $var

相关标签:
4条回答
  • 2020-12-14 05:18

    Jon is right. Here's an example:

    $this->db->select('movies.id, 
                       movies.title, 
                       movies.year, 
                       movies.runtime as totaltime,  
                       posters.poster_url');
    $this->db->from('movies');
    $this->db->join('posters', 'movies.id= posters.id');
    $this->db->where('movies.id', $id);
    $q = $this->db->get();
    

    This will return objects that have ->id, ->title, ->year, ->totaltime, and ->poster_url properties. You won't need the additional code to fetch the data from each row.

    Don't forget, if the Active Record syntax gets a little unwieldy, you can use full SQL queries and get the same results:

    $sql = "SELECT movies.id,
            movies.title,
            movies.year,
            movies.runtime as totaltime,
            posters.poster_url
            FROM movies
            INNER JOIN posters ON movies.id = posters.id
            WHERE movies.id = ?"
    
    return $this->db->query($sql, array($id))->result();
    

    Both forms will ensure that your data is escaped properly.

    CodeIgniter Active Record

    Query Binding in CodeIgniter

    0 讨论(0)
  • 2020-12-14 05:30

    An asterisk will return all the fields. To return a subset of these, i.e. all fields apart form the repeated id field, simply list the columns which you require rather than use '*'.

    It is often a good idea to not use asterisk anyway. In the future of the app, someone may add a large field to the table which will be surplus to your requirements, and will slow your queries.

    0 讨论(0)
  • 2020-12-14 05:35

    Simply put with method chaining:

    $this->db->select('*')
             ->from('movies')
             ->join('posters', 'movies.id= posters.id')
             ->where('movies.id', $id)
             ->get();
    
    0 讨论(0)
  • 2020-12-14 05:37
    $this->db->select('*');
    $this->db->from('blogs');
    $this->db->join('comments', 'comments.id = blogs.id');
    $query = $this->db->get();
    
    0 讨论(0)
提交回复
热议问题