Jonathan Jonathan - 1 year ago 68
PHP Question

CodeIgniter/PHP/MySQL: Retrieving data with JOIN

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 $variable... How can I do it and get all the fields without the primary key field???

What I'm doing now is this (only two tables joined here):

function getAll($id) {

$this->db->join('posters', '');
// WHERE id = $id ... goes here somehow...
$q = $this->db->get();

if ($q->num_rows() == 1) {
$row = $q->row();
$data = array(
'id' => $row->id,
'title' => $row->title,
'year' => $row->year,
'runtime' => $row->runtime,
'plotoutline' => $row->plotoutline,
'poster_url' => $row->poster_url

return $data;

id (PK), title, year, runtime and plotoutline are columns from the first table and poster_url is a field from the second table. The second table also contains an ID (PK) column that I don't want to Retrieve because I already have.

Answer Source

Jon is right. Here's an example:

                   movies.runtime as totaltime,  
$this->db->join('posters', '');
$this->db->where('', $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.runtime as totaltime,
        FROM movies
        INNER JOIN posters ON =
        WHERE = ?"

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download