CodeIgniter MySQL查询不起作用

时间:2011-01-29 19:47:32

标签: php mysql codeigniter activerecord

我正在尝试让这个查询在CodeIgniter中运行,但它正在吐出一个错误:

  

发生数据库错误错误   编号:1096

     

没有使用表格

     

SELECT *

如果我将查询直接放入MySQL,它可以正常工作(我用值替换$ variables)。以下是查询作为codeigniter的输入:

$this->db->query(" 
    SELECT * 
    FROM writing_quests 
    LEFT OUTER JOIN members_quests_completed 
    ON members_quests_completed.quest_id = writing_quests.id 
    WHERE writing_quests.level_required <=  $userlevel 
    AND ( 
        members_quests_completed.user_id = $user_id
        OR 
        members_quests_completed.user_id IS NULL )"
);
$query = $this->db->get();

我做错了什么,我错过了吗? 我已经包含了整个函数调用,以防问题出在其他地方?我已经多次做过这件事而没有任何问题。

function get_all_quests_for_user() {
    $user_id = $this->session->userdata('user_id');
    $userlevel = $this->session->userdata('user_level');

    $this->db->query("SELECT writing_quests.id, writing_quests.points_availible, writing_quests.name, writing_quests.note, writing_quests.instructions, writing_quests.time_limit, members_quests_completed.location_completed, members_quests_completed.status  FROM writing_quests LEFT OUTER JOIN members_quests_completed ON members_quests_completed.quest_id = writing_quests.id WHERE writing_quests.level_required <=  '$userlevel' AND writing_quests.unlocked = 1 AND ( members_quests_completed.user_id = '$user_id' OR members_quests_completed.user_id IS NULL )");
    $query = $this->db->get();
    $this->db->last_query();
    return $query->result();
}

2 个答案:

答案 0 :(得分:6)

我认为应该是这样的:

$query = $this->db->query(" 
SELECT * 
FROM writing_quests 
LEFT OUTER JOIN members_quests_completed 
ON members_quests_completed.quest_id = writing_quests.id 
WHERE writing_quests.level_required <=  $userlevel 
AND ( 
    members_quests_completed.user_id = $user_id
    OR 
    members_quests_completed.user_id IS NULL )"
);

或者:

$query = $this->db->get('mytable');

答案 1 :(得分:5)

SELECT writing_quests.*, ( put needed fields from members_quests_completed ) 
FROM writing_quests
LEFT JOIN members_quests_completed ....

相同的字段名称会破坏结果对象

中的结果列名称

因为使用*不明智,你应该有字段列表...
什么是最重要的:

$result = $this->db->query ( ... );
当你将数据分配给变量时,INSERT或UPDATE(主要是),

$ this-&gt; db-&gt;查询(...)是好的:http://codeigniter.com/user_guide/database/results.html