简体   繁体   English

如何在PHP中将数据数组插入到mysql数据库中?

[英]How to insert array of data in to mysql database in PHP?

My problem is that an array of data is not inserted to the database only last data is inserted.我的问题是数据数组没有插入到数据库中,只插入了最后一个数据。 So, how to insert whole data at a time after click save button?那么,如何在单击保存按钮后一次插入整个数据? I am using Codeigniter framework.我正在使用 Codeigniter 框架。

Can anyone help me in fixing this issue because I am new to Codeigniter?任何人都可以帮助我解决这个问题,因为我是 Codeigniter 的新手吗? Thank you.谢谢你。

Here is my Controller Part.这是我的控制器部分。 Please review this code and let me know if something is incorrect.请查看此代码,如果有什么不正确,请告诉我。

                    function index(){
                        $this->session->set_userdata('top_menu', 'Attendance');
                            $this->session->set_userdata('sub_menu', 'teacherattendance/index');
                            $teacher_result = $this->teacher_model->get();
                            $data['teacherlist'] = $teacher_result;

                            $this->form_validation->set_rules('stime', 'In Time', 'trim|required|xss_clean');
                            $this->form_validation->set_rules('etime', 'Out Time', 'trim|required|xss_clean');
                            if ($this->form_validation->run() == FALSE) { 
                        $this->load->view('layout/header', $data);
                        $this->load->view('admin/teacherattendance/attendenceList', $data);
                        $this->load->view('layout/footer', $data);
                            } else {
                            $data = array(
                                    'in_time' =>$this->input->post('stime'),
                                    'out_time' => $this->input->post('etime'),
                                    'teacher_id' => $this->input->post('teacter_id'),
                                    //'teacher_name' => $this->input->post('teacher_name')
                                    ); 

                        $this->load->model('teacherattendance_model');
                        $insert_id = $this->teacherattendance_model->add($data);
                        $this->session->set_flashdata('msg', '<div class="alert alert-success">Attendance added Successfully</div>');
                               redirect('admin/teacherattendance');

                        }
                        }

Here is my Model Part.这是我的模型部分。 Please check.请检查。 This project for school erp.这个项目为学校 erp。

                    public function add($data) {
                            if (($data['id']) != 0) {
                                $this->db->where('id', $data['id']);
                                $this->db->update('teacher_attendance', $data); // update the record
                            } else {
                                $this->db->insert('teacher_attendance', $data); // insert new record
                                return $this->db->affected_rows();
                            }
                        }

Here is my View Part, please check.这是我的查看部分,请检查。

                # View 

                <style type="text/css">
                    @media print
                    {
                        .no-print, .no-print *
                        {
                            display: none !important;
                        }
                    }
                </style>

                <div class="content-wrapper" style="min-height: 946px;">  
                    <section class="content-header">
                        <h1>
                            <i class="fa fa-mortar-board"></i> Teacher Attendance <small><?php echo $this->lang->line('student_fees1'); ?></small></h1>
                    </section>
                    <!-- Main content -->
                    <section class="content">
                        <div class="row">       

                            <div class="col-md-12">              
                                <div class="box box-primary" id="tachelist">
                                    <div class="box-header ptbnull">
                                        <h3 class="box-title titlefix"><?php echo $this->lang->line('teacher_list'); ?></h3>
                <div class="box-tools pull-right">
                                            <a href="<?php echo base_url(); ?>admin/teacherattendance/import" class="btn btn-primary btn-sm"  data-toggle="tooltip" title="Bulk Upload Teacher Attendance" >
                                                <i class="fa fa-upload"></i>Import Teacher Attendance
                                            </a>
                                        </div>     
                <div class="exportteacher">
                                            <a href="<?php echo base_url(); ?>admin/teacherattendance/exportCSV" class="btn btn-primary btn-sm"  data-toggle="tooltip" title="Download Teacher Attendance" >
                                                <i class="fa fa-download"></i>Export Teacher Attendance
                                            </a>
                                        </div>                
                </div>
                                    <div class="box-body">
                                        <div class="mailbox-controls">
                                        </div>
                                        <div class="table-responsive mailbox-messages">
                                        <div class="download_label"><?php echo $this->lang->line('teacher_list'); ?></div>
                                            <form role="form" id=""  class="addmarks-form"  method="post" action="<?php echo site_url('admin/teacherattendance/') ?>">
                                            <?php if ($this->session->flashdata('msg')) { ?>
                                                        <?php echo $this->session->flashdata('msg') ?>
                                                    <?php } ?>  
                                                    <?php echo $this->customlib->getCSRF(); ?>
                                                    <div class="table-responsive">
                                                        <table class="table table-striped table-hover">
                                                            <thead>
                                                                <tr>

                                                                    <th>
                                                                        Teacher Name
                                                                    </th>

                                                                    <th>
                                                                        Phone
                                                                    </th>
                                                                    <th>
                                                                        In Time
                                                                    </th>
                                                                    <th>
                                                                        Out Time
                                                                    </th>

                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                            <?php
                                                    $count = 1;
                                                                foreach ($teacherlist as $teacher) {
                                                        ?>
                                                        <input type="hidden" name="teacter_id" value="<?php echo $teacher['id'] ?>">

                                                                    <tr>

                                                                        <th name="teacher_name">
                                                                            <?php echo $teacher['name'] ?>
                                                                        </th>

                                                                        <th>
                                                                            <?php echo $teacher['phone'] ?>
                                                                        </th>
                                                                        <th>
                                                                            <div class="bootstrap-timepicker">
                                                                                <div class="form-group">
                                                                                    <div class="input-group">
                                                                                        <input type="text" name="stime" class="form-control timepicker" 
                                                                                          id="stime" value="<?php echo $value->starting_time; ?>">                                                                                      
                                                                                        <div class="input-group-addon">
                                                                                            <i class="fa fa-clock-o"></i>
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        </th>
                                                                        <th>
                                                                            <div class="bootstrap-timepicker">
                                                                                <div class="form-group">
                                                                                    <div class="input-group">
                                                                                        <input type="text" name="etime" class="form-control timepicker" id="etime" value="<?php echo $value->ending_time; ?>">
                                                                                        <div class="input-group-addon">
                                                                                            <i class="fa fa-clock-o"></i>
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        </th>

                                                                    </tr>
                                                              <?php
                                                    }
                                                    $count++;
                                                    ?>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <button type="submit" class="btn btn-primary pull-right" name="save_attendance" value="save_attendance"><?php echo $this->lang->line('save'); ?></button>
                                                </form>
                                        </div>
                                    </div>
                                    <div class="">
                                        <div class="mailbox-controls">
                                        </div>
                                    </div>
                                </div>
                            </div> 
                        </div>
                    </section>
                </div>
        //  This is Javascript Part so ignore please...
                <link rel="stylesheet" href="<?php echo base_url() ?>backend/plugins/timepicker/bootstrap-timepicker.min.css">                  
                <script src="<?php echo base_url() ?>backend/plugins/timepicker/bootstrap-timepicker.min.js"></script>          
                <script>    
                $(function () {

                        $(".timepicker").timepicker({
                            showInputs: false,
                            defaultTime: false,
                            explicitMode: false,
                            minuteStep: 1
                        });
                    });
                </script>
                <script type="text/javascript">
                    var base_url = '<?php echo base_url() ?>';
                    function printDiv(elem) {
                        Popup(jQuery(elem).html());
                    }

                    function Popup(data)
                    {

                        var frame1 = $('<iframe />');
                        frame1[0].name = "frame1";
                        frame1.css({"position": "absolute", "top": "-1000000px"});
                        $("body").append(frame1);
                        var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
                        frameDoc.document.open();
                        //Create a new HTML document.
                        frameDoc.document.write('<html>');
                        frameDoc.document.write('<head>');
                        frameDoc.document.write('<title></title>');
                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/bootstrap/css/bootstrap.min.css">');
                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/font-awesome.min.css">');
                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/ionicons.min.css">');
                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/AdminLTE.min.css">');
                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/skins/_all-skins.min.css">');
                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/iCheck/flat/blue.css">');
                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/morris/morris.css">');


                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/jvectormap/jquery-jvectormap-1.2.2.css">');
                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/datepicker/datepicker3.css">');
                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/daterangepicker/daterangepicker-bs3.css">');
                        frameDoc.document.write('</head>');
                        frameDoc.document.write('<body>');
                        frameDoc.document.write(data);
                        frameDoc.document.write('</body>');
                        frameDoc.document.write('</html>');
                        frameDoc.document.close();
                        setTimeout(function () {
                            window.frames["frame1"].focus();
                            window.frames["frame1"].print();
                            frame1.remove();
                        }, 500);


                        return true;
                    }
                </script>

I have this abit of a solution, maybe better if you make a model in core folder, for example,我有这个解决方案,如果你在核心文件夹中制作一个模型可能会更好,例如,

Core_Model:核心_型号:

class Core_Model extends CI_Model
{
   protected $table = '';

   public function insertItem($in_data)
   {
      $this->db->insert($this->table, $in_data); //query for inserting
      $last_id = $this->db->insert_id(); //if you want to get the last id inserted

      return $last_id;
   }
}

My_Model我的模型

class My_Model extends Core_Model
{
   public function __construct()
   {
      $this->table = 'my_table';
   }
}

In this way though, every table needs to be one Model, for example table_user , that should be one Model, probably name it User_Model or something, in that way every single time instead of making lots of insert functions you can just call the core insertItem() function for convenience.通过这种方式,每个表都需要是一个模型,例如table_user ,这应该是一个模型,可能将其命名为User_Model或其他名称,这样每次都可以调用核心 insertItem 而不是创建大量插入函数() 函数为方便起见。

Example例子

My_Controller我的控制器

class My_Controller extends CI_Controller
{
   public function add()
   {
      $this->load->model('User_model');

      $data = array(
         'username'=>$this->input->post('username'),
         'password'=>$this->input->post('password')
      );

      $this->user_model->insertItem($data); //since user_model extends the core file, it can access the method insertItem() as long as it is public
   }
}

Note: that this will only work with one table注意:这只适用于一张桌子

<?php
function mysql_insert_array($table, $data, $exclude = array()) {
    $fields = $values = array();
    if( !is_array($exclude) ) $exclude = array($exclude);
    foreach( array_keys($data) as $key ) {
        if( !in_array($key, $exclude) ) {
            $fields[] = "`$key`";
            $values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
        }
    }
    $fields = implode(",", $fields);
    $values = implode(",", $values);
    if( mysql_query("INSERT INTO `$table` ($fields) VALUES ($values)") ) {
        return array( "mysql_error" => false,
                      "mysql_insert_id" => mysql_insert_id(),
                      "mysql_affected_rows" => mysql_affected_rows(),
                      "mysql_info" => mysql_info()
                    );
    } else {
        return array( "mysql_error" => mysql_error() );
    }
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM