如何在 codeigniter 中插入具有新增量的值?

How to insert value with new increment in codeigniter?

public function myfuntion() {
    if($_POST){
        $urnno = "NU-62819100";
        $data = array(
                    "name" => $this->input->post('name'),
                    "email" => $this->input->post('email'),
                    "phone" => $this->input->post('phone'),
                    "urnno" => $urnno + 1
                );
        $sql = $this->db->insert('student',$data);
        if($sql){
            echo "success";
        }else{
            echo "fail";
        }
    }
    $this->loca->view('myform');
}

在这段代码中,我只是简单地插入表单值,但是当我插入值时,这里发生的事情 urnno 必须在新插入后自动递增,就像我第一次插入值时那样 urnno 必须是 NU-62819101 第二次它将是 102 然后 103 像这样。那么,我该怎么做呢?请帮助我。

谢谢

可以先把最后一个urnno存入table,取其数值部分自增,然后存入table

我已经为您的问题写了一个可能的解决方案,必要时会提到评论。看看它是否对你有帮助。

public function myfuntion() {

    if($_POST){

        // get the last row saved in table
        $last = $this->db->select('urnno')->from('student')->order_by('id', 'DESC')->get()->row(); // id or some other auto incremented field

        // get urnno from the last row
        $last_urnno = $last->urnno;

        $last_arr = explode("-", $last_urnno); // make it an array to get the numerical part

        $new = $last_arr[1] + 1; // increment the value

        $urnno = "NU-{$new}"; // new value

        $data = array(
                    "name" => $this->input->post(''),
                    "email" => $this->input->post(''),
                    "phone" => $this->input->post(''),
                    "urnno" => $urnno // new value
                );

        $sql = $this->db->insert('student', $data);

        if($sql){
            echo "success";
        }else{
            echo "fail";
        }
    }
    $this->loca->view('myform');
}

如果您只增加值为 1 的列,那么您可以尝试在数据库中设置自动增加的列。它使更容易并删除不需要的计算。