Jon*_*han 6 php mysql codeigniter
我是PHP/MySQL的新手,也是CodeIgniter的新手.我在许多MySQL表中都有信息.我想用JOIN检索它,其中表主键等于$ variable ...我怎么能这样做并获得没有主键字段的所有字段???
我现在正在做的是这里(这里只有两个表加入):
function getAll($id) {
$this->db->select('*');
$this->db->from('movies');
$this->db->join('posters', 'movies.id= posters.id');
// 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
);
}
$q->free_result();
return $data;
Run Code Online (Sandbox Code Playgroud)
id(PK),title,year,runtime和plotoutline是第一个表中的列,poster_url是来自第二个表的字段.第二个表还包含一个我不想检索的ID(PK)列,因为我已经有了.
Glo*_*ish 21
乔恩是对的.这是一个例子:
$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();
Run Code Online (Sandbox Code Playgroud)
这将返回具有 - > id, - > title, - > year, - > totaltime和 - > poster_url属性的对象.您不需要额外的代码来从每行获取数据.
不要忘记,如果Active Record语法变得有点笨拙,您可以使用完整的SQL查询并获得相同的结果:
$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();
Run Code Online (Sandbox Code Playgroud)
这两种表单都将确保您的数据正确转义.
| 归档时间: |
|
| 查看次数: |
26900 次 |
| 最近记录: |