CodeIgniter、Ajax...如何使用 insert_id()

CodeIgniter, Ajax... How to use insert_id()

提问人:Nira 提问时间:7/24/2018 最后编辑:Nira 更新时间:7/24/2018 访问量:662

问:

对不起,我的英语,我希望你能理解我的问题......

在我的程序中,当您使用模态+表单向数据库(MySQL)提交新记录时,它会被绘制在数据表中,而无需刷新或为实际页面充电,它是动态附加的。

我需要做的是,在每条新记录中,使用新数据的 ID 绘制/附加数据和 2 个按钮(1 个用于删除该记录,1 个用于更新它)。

我读到我可以使用 insert_id() 来获取最后插入的 id,但我不知道如何使用它以及如何在我的 Ajax 调用中使用结果。

有什么提示吗?我是编程的新手。

感谢您抽出时间接受采访。

编辑

我需要我在模态/表单中引入的数据(为此我使用的是 .serialize())和数据库中生成的 ID...... 我不知道如何使用模型/控制器返回的 ID 信息。

我的控制器中有这个:

    public function nuevo_elemento_diccionario()
{
    $this->load->helper('form');
    $this->load->library('form_validation');

    // Validation rules that I deleted for this post
    if ($this->form_validation->run() === FALSE)
    {              
        $this->load->view("header");
        $this->load->view("section-aside");
        $this->load->view("vista_nuevo_elemento_diccionario", $datos);
        $this->load->view("footer");
    }
    else
    {
        $last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
        echo json_encode(array('last_id' => $last_id));
        redirect('/diccionarios/lista_diccionarios');
    }
}

型:

public function nuevo_elemento_diccionario()
 {
     $datos = array(
        'ELDI_Key' => $this->input->post('eldi_key'),
        'ELDI_Display' => $this->input->post('eldi_display'),
        'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
    );
    $this->db->insert('elementos_diccionario', $datos);
   /* $ultima_id = $this->db->insert_id();*/
    $last_id = $this->db->insert_id();
    return  $last_id;
  }

Javascript/Ajax(你看到 var key = $('input[name=“eldi_key”]').val(); 使用它,是我需要使用 ID 使用新 ID 的地方,单击生成的按钮进行删除和更新):

function nuevo_elemento() 
{
    var id =$('input[name="eldi_id"]').val();
    var display = $('input[name="eldi_display"]').val();
    var key = $('input[name="eldi_key"]').val();
    key = key.split(" ").join("_").toLowerCase();

    swal({
        title: 'Añadir elemento',
        text: "¿Quieres añadir este elemento?",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Sí',
        cancelButtonText: 'No'
        }).then((result) => {
        if (result.value) {
            $.ajax({
                type: "POST",
                url: $("#base_url").attr("valor") + 
 "diccionarios/nuevo_elemento_diccionario",
                data: $("#formNuevoElementoDiccionario").serialize(),
                success: function(data) {
                    console.log(data);
                    $('#Modal_Add').modal('hide');

                    $("#formNuevoElementoDiccionario").trigger("reset");

                    var html = 
                    '<tr>'+
                        '<td>' + key + '</td>' +
                        '<td>'+ display +'</td>'+
                        '<td>'+
                            '<span class="btn btn-default editar_elemento" 
 id=' + key + ' value="' + key + '">' +
                                '<a href="'+$("#base_url").attr("valor") + 
 "diccionarios/elemento_diccionario/"+key+'" title="Editar">' +
                                    '<i class="material-icons">edit</i>' +
                                '</a>' +
                            '</span>' +
                        '</td>' + 
                        '<td>' +
                            '<span class="btn btn-default borrar_elemento" 
 id="'+ key +'" value="'+ key +'">'+
                                    '<i class="material- 
 icons">delete_outline</i>'+   
                            '</span>'+
                        '</td>'+
                    '</tr>'

                    $('#tabla-diccionarios').append(html);
                    swal("Añadido", "Elemento añadido correctamente", 
"success");

                    $(".borrar_elemento").off();                        
                    evento_borrar_elemento();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log("Error: " + textStatus);
                    }
            });
        }
        })
}
php mysql ajax codeigniter 插入 id

评论

1赞 Niklesh Raut 7/24/2018
您可以添加上次更新数据以显示插入了 ID 的记录。
0赞 Alex 7/24/2018
从字面上看,有很多方法可以做到这一点,以至于不可能知道哪一种适合您。请分享您的代码并阅读 stackoverflow.com/help/mcve
0赞 Nira 7/24/2018
我编辑了我的问题,希望现在更清楚了......对不起,伙计们
0赞 GGw 7/24/2018
$ret = $this->db->insert_id(); return $ret;在模型中尝试此操作
0赞 Nira 7/24/2018
我再次用代码编辑,有了这个 ->我需要我在模态/表单中引入的数据(为此我使用的是 .serialize())和数据库中生成的 ID......

答:

1赞 zahorniak 7/24/2018 #1

只有在向 DB 插入数据后才能使用 insert_id()。如果你在控制器或js中需要用户最后一个id,试试这个:

public function nuevo_elemento_diccionario()
{
    $datos = array(
        'ELDI_Key' => $this->input->post('eldi_key'),
        'ELDI_Display' => $this->input->post('eldi_display'),
        'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
    );
    $this->db->insert('elementos_diccionario', $datos);
    $ultima_id = $this->db->insert_id();
    return $ultima_id;
}

然后你可以使用 json_encode() 在 Controller 中将数据返回给 js:

public function nuevo_elemento_diccionario()
{
    $this->load->helper('form');
    $this->load->library('form_validation');

    // Validation rules that I deleted for this post
    if ($this->form_validation->run() === FALSE)
    {              
        $this->load->view("header");
        $this->load->view("section-aside");
        $this->load->view("vista_nuevo_elemento_diccionario", $datos);
        $this->load->view("footer");
    }
    else
    {
        $last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
        echo json_encode(array('last_id' => $last_id));
        // i`m not sure that you need to use redirect
        redirect('/diccionarios/lista_diccionarios');
    }
}

在 js 编辑成功函数中:

 success: function(data) {
     var result = JSON.parse(data);
     var insert_id = result.insert_id;

评论

0赞 Nira 7/24/2018
我无法让它工作......如何在ajax中使用id?使用insert_id变量而不是$key?
0赞 Nira 7/24/2018
我再次用这个编辑 -> 我需要我在模态/表单中引入的数据(为此我使用的是 .serialize())和数据库中生成的 ID......