codeigniter:从数据库编辑和删除

时间:2016-01-09 17:43:54

标签: codeigniter codeigniter-2

我在编码/删除数据库中的问题时遇到问题。从我的测验问题。这是我的模特。我想通过控制器从视图中编辑一个问题。

这是我目前的模式:

function getquestions($quizid)
{
    // get data about the quiz - we need the quiz size
    $quiz = $this->getquiz($quizid);
    $qzsize = $quiz['quizsize'];

    $this->db->select('id'); // we want just the id fields
    $this->db->limit($qzsize); // how many questions to ask

    // this next clause allows us to select random questions - a full discussion of how this works and its drawbacks is

    // here https://www.warpconduit.net/2011/03/23/selecting-a-random-record-using-mysql-benchmark-results/

    $this->db->order_by('RAND()');
    $res = $this->db->get_where('questions',array('quizid' => $quizid));
    log_message('DEBUG',$this->db->last_query());
    if ($res->num_rows() == 0) {

        // no questions found!

        // returning false to controller tells it we have encountered an error

        // leave controller to decide how to handle error
        return false;
    }

    $questions = array();
    foreach ($res->result_array() as $row) {
        $questions[] = $row['id'];
    }
    shuffle($questions); // provide questions in random order
    $res->free_result();
    return $questions;
}
/**
 * get a question

 * @param int - question id

 * @return mixed false|array - question data + answers (array)
 */
function getquestion($id) {
    $this->db->where('id',$id);
    $res = $this->db->get('questions');
    if ($res->num_rows() != 1) {
        return false;
    }
    $question = $res->row_array(); // get first row as an array - this is the question data

    // now get the answers for this question

    $res = $this->db->get_where('answers',array('questionid' => $id));
    if ($res->num_rows() < 2) {

        // must have at least two answers
        return false;
    }
    $answers = array();
    // get each row as an array and push it onto the answers array

    foreach ($res->result_array() as $row) {
        $answers[] = $row;
    }
    shuffle($answers);
    // now return all the data as one array, with keys to help access elements

    return array('q' => $question,'a' => $answers);
}

1 个答案:

答案 0 :(得分:0)

在你控制器的某个地方,你需要检测到“删除”&#39;行动。这可能是通过URL或通过表单输入。我相信你能做到这一点。

例如,控制器可能将其方法定义为

public function view($question_id=0, $action='') { 

然后,您的网页上可能会有一个链接,其中的操作部分已定义为&#39; delete&#39;。在你的控制器中你会有一个

if ($action == 'delete') {

要从数据库中删除所选问题,您可以使用

$this-db-where('question_id', $question_id);
$this->db->limit(1);
$this->db->delete('my_table');

这里有详细描述: http://www.codeigniter.com/userguide3/database/query_builder.html#deleting-data

要编辑数据,您需要收集表单输入:

http://www.codeigniter.com/userguide3/libraries/input.html

使用错误检查的输入值,使用查询构建器(链接到之前的链接)将新数据发布到数据库。

这样的东西
$data = array(
   'name' => $name,
   'description' => $description;
);
$this-db-where('question_id', $question_id);
$this->db->update('mytable', $data);

我希望在某种程度上有所帮助,或者如果没有,请在您的问题中更具体。

祝你的网站好运,

祝福,