如何在php中向mysql数据库中插入数据数组?

n3h0vuf2  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(317)

我的问题是没有将数据数组插入到数据库中,只插入最后一个数据。那么,如何在单击“保存”按钮后一次插入整个数据呢?我正在使用codeigniter框架。
有谁能帮我解决这个问题,因为我是新的codeigniter?谢谢您。
这是我的控制器部分。请检查此代码,如果有错误请告诉我。

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

                        }
                        }

这是我的模型部分。请检查一下。本项目为学校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();
                            }
                        }

这是我的视图部分,请检查。


# 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>
oxiaedzo

oxiaedzo1#

我有一个解决方案,如果你在核心文件夹里做一个模型也许更好,例如,
核心模型:

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

我的\u模型

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

但是,以这种方式来说,每个表都需要是一个模型 table_user ,这应该是一个模型,可能是它的名字 User_Model 或者类似的,每次都可以调用core insertitem()函数,而不是生成大量的insert函数。
例子
我的\u控制器

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

注意:这只适用于一个表

0h4hbjxa

0h4hbjxa2#

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

相关问题