如何使用jquery将html表单字段作为数组直接传递给codeigniter中的数据库

bxgwgixi  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(290)

这是我的查看页面:

<form role="form" id="addNewMatter" action="<?php echo base_url() ?>saveNewSupplier" 
method="post">

<input type="text" value="" name="name" id="name" />
<input type="text" value="" name="phone" id="phone" />
<input type="text" value="" name="email" id="email" />
<input type="text" value="" name="address" id="address" />

<script>
   $('form').change(function() {
       var input = $('form').serializeArray();
       var data = "";
       $( "#formdata" ).empty();
       jQuery.each( input, function( i, input1 ) {
        if($(this).attr("name") !== 'formdata'){
         data += "\"" + $(this).attr("name") + "\"=>" +  "\"" + input1.value +  "\",";
        }
           finaldata = data.replace(/,\s*$/, "");
           $( "#formdata" ).val( finaldata );
           //alert($(this).attr('name'));
        });
    });
</script>

<input type="text" value="" name="formdata" id="formdata" />
</form>

这是我的控制器页面:

function saveNewSupplier()
{

    $createdby= $this->vendorId;
    $createddate= date('d M Y');

            $formdata = $this->input->post('formdata');
$Info = array();
    $Info = array($formdata, 'createdby'=>$createdby,
   'createddate'=>$createddate);
$this->load->model('user_model');
$result = $this->user_model->saveNewSupplier($Info);
}

这是我的模型页面:

function saveNewSupplier($Info)
{
    $this->db->trans_start();
    $this->db->insert('tbl_suppliers1', $Info);

    $insert_id = $this->db->insert_id();

    $this->db->trans_complete();

    return $insert_id;
}

插入查询不起作用,它显示 0 作为数组中的第一列,但它应该是我通过post方法从视图传递的数组。请帮助我修复此插入查询。谢谢。

efzxgjgh

efzxgjgh1#

$this->input->post() 将表单字段作为数组提供给您,因此您无需使用任何javascript即可完成此操作。
如果你的 tbl_suppliers1 表中有“formdata”、“createdby”、“createddate”列:

function saveNewSupplier()
{
    $createdby = $this->vendorId;
    $createddate = date('d M Y');

    $form = $this->input->post();
    $data = array(
        json_encode($form),
        'createdby' => $createdby,
        'createddate' => $createddate
    );
    $this->load->model('user_model');
    $result = $this->user_model->saveNewSupplier($data);
}

如果你的 tbl_supplier 有“name”、“phone”、“etc”、“createddate”列:

function saveNewSupplier()
{
    $createdby = $this->vendorId;
    $createddate = date('d M Y');

    $form = $this->input->post();
    $data = $form;
    $data['createdby'] = $createdby;
    $data['createddate'] = $createddate;
    $this->load->model('user_model');
    $result = $this->user_model->saveNewSupplier($data);
}

请记住,脚本方法或以上示例都不会检查有效字段。

相关问题