$ this-> db-> insert_id()似乎正在抹去我以前的insert_id变量值

时间:2011-11-22 10:07:27

标签: php mysql codeigniter variables

以下是代码:

$the_question = $_POST['question'];
            $the_answer = $_POST['answer'];
            $dummy_num[] = $_POST['dummy_answer_1'];
            $dummy_num[] = $_POST['dummy_answer_2'];
            $dummy_num[] = $_POST['dummy_answer_3'];
            //Get Hidden Test ID and Q_order
            $test_id = $_POST['test_id'];
            $q_order = $_POST['q_order'];
            //Submit Question
            $data_submit_q = array (
                'type' => 1,
                'question' => $the_question,
                'done' => 1
            );
            $this->db->where('test_id', $test_id);
            $this->db->where('q_order', $q_order);
            $this->db->update('questions', $data_submit_q);
            $question_id = $this->db->insert_id();
            $time_created = date('Y-m-d H:i:s');
            //Submit Answer 
            $data_submit_a = array (
                'test_id' => $test_id,
                'question_id' => $question_id,
                'option' => $the_answer,
                'company_id' => $data['company']->id,
                'job_id' => $data['session_job_id'],
                'time_created' => $time_created
            );
            $this->db->insert('options', $data_submit_a);
            $answer_id = $this->db->insert_id();

            //Let question know that answer is right.
            $data_submit_qr = array (
                'answer_id' => $answer_id
            );

            $this->db->where('id', $question_id);
            $this->db->where('test_id', $test_id);
            $this->db->update('questions', $data_submit_qr);

设置答案ID会删除问题ID的值,然后在更新数据库时,答案ID也没有值。即使它之前就是这样。

2 个答案:

答案 0 :(得分:4)

方法$this->db->insert_id()在执行数据库插入时检索ID(如名称提示)。

你在更新后使用它,这就是你的$question_id给出问题的原因(我认为它会被设置为FALSE,但我不确定该方法在被错误调用时会返回什么上下文)。当您进行上次更新时,将其用作WHERE条件,如果未设置...

这不是你第二次调用insert_id()消除了第一个,我怀疑更像是第一个已经没有设置(或假)

答案 1 :(得分:0)

似乎insert_id存在错误,您可以尝试使用:

$query = $this->db->query('SELECT LAST_INSERT_ID()');
  $row = $query->row_array();
  $lastInsertId = $row['LAST_INSERT_ID()'];

希望有所帮助