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

标签 php mysql ajax codeigniter insert-id

请原谅我的英语,我希望你能理解我的问题...

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

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

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

请问有什么提示吗?我对编程还很陌生。

感谢您的宝贵时间。

编辑

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

我的 Controller 中有这个:

    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);
                    }
            });
        }
        })
}

最佳答案

只有在将数据插入到数据库后才能使用insert_id()。如果您需要 Controller 或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;

关于php - CodeIgniter、Ajax...如何使用 insert_id(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51492828/

相关文章:

javascript - 为什么我的回调函数不起作用?

php - 如何为 Centos 安装 php-mysqli 包

php - POST 可以进行 SQL 注入(inject)吗?

php - 表单字段已经填写

php - 在数据库中插入多个电子邮件(唯一键)行

jquery - 设置请求 header 时,在预检响应错误中,Access-Control-Allow-Headers 不允许请求 header 字段授权

php - 组合多个唯一的 MySQL 表并按一列排序,#2

PHP循环遍历一半数组

php - 使用 php 记录用户登录时间并在网站上显示

javascript - 具有回调函数的 AJAX