CodeIgniter Forums
facing problems with inserting data - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: facing problems with inserting data (/showthread.php?tid=70019)

Pages: 1 2 3


facing problems with inserting data - CharlesK - 02-10-2018

Hello guys, i am totally new in codeigniter and have gone through its documentation which is very nice, though am having problems inserting data to MySql as my view has a date and rime picker and a static sender,Please help.
Here is my code:this is my model,controller and view respectively
Code:
<?php

if (!defined('BASEPATH'))
   exit('No direct script access allowed');

class sms extends CI_Model {

   function insert_data() {

       $this->db->insert('sms_log', $data);
       $smsid = $this->db->insert_id();
       
}
   return $smsid;


}

/* End of file sms.php */    
respectively
Code:
<?php

if (!defined('BASEPATH'))
   exit('No direct script access allowed');

class sms extends CI_Controller {

   function __construct() {
       parent::__construct();
       $this->config->load('facebook');
       $this -> load -> library(array('form_validation'));
       $this->load->library('encrypt');
       $this->load->model('countries');
       $this->load->model('users');
       $this->load->model('sms');

}
   function index() {
       $this->load->view('modal_send_sms');
   }
   public function sms_form(){
       $save = array(
                       'sender'            =>$this->input->post('sender');
                       'recepients'        =>$this->input->post('recepients');
                       'body'              =>$this->input->post('body');
                       'sendscheduletime'  =>$this->input->post('sendscheduletime');
       )
       $this->sms->savesms($save);
       redirect('modal_send_sms');
   }



}

/* End of file sms.php */    


Code:
<link href="<?php echo base_url() ?>assets/css/bootstrap-timepicker.min.css" rel="stylesheet">
<link href="<?php echo base_url() ?>assets/css/datepicker3.css" rel="stylesheet">
<link href="<?php echo base_url() ?>assets/tagsinput/bootstrap-tagsinput.css" rel="stylesheet">

<script type="text/javascript" src="<?php echo base_url() ?>assets/js/bootstrap-timepicker.js"></script>
<script type="text/javascript" src="<?php echo base_url() ?>assets/js/bootstrap-datepicker.js"></script>

<script type="text/javascript" src="<?php echo base_url() ?>assets/js/typeahead.js/bloodhound.min.js"></script>
<script type="text/javascript" src="<?php echo base_url() ?>assets/js/typeahead.js/typeahead.bundle.min.js"></script>
<script type="text/javascript" src="<?php echo base_url() ?>assets/js/typeahead.js/typeahead.jquery.min.js"></script>

<script type="text/javascript" src="<?php echo base_url() ?>assets/tagsinput/bootstrap-tagsinput-angular.min.js"></script>
<script type="text/javascript" src="<?php echo base_url() ?>assets/tagsinput/bootstrap-tagsinput.min.js"></script>



<button class="btn btn-primary btn-xs pull-right" data-toggle="modal" data-target="#myModal">
   Send Message
</button>
<style type="text/css">
   .modal-backdrop{z-index: 1200;}
   .modal{z-index: 1201;}
   .tt-dropdown-menu{z-index: 1203; border: solid 1px #CCC; margin-right: 0; margin-left: 0; background-color: #fff; border-color: #ddd; border-width: 1px; border-radius: 4px 4px 0 0; border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; -webkit-box-shadow: none; box-shadow: none;}
   .tt-suggestions{}
</style>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="z-index: 9999;">
   <div class="modal-dialog">
       <div class="modal-content">
           <div class="modal-header">
               <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
               <h4 class="modal-title" id="myModalLabel">Send Message</h4>
           </div>
           <div class="modal-body">
               <form name="SendSMSForm" id="SendSMSForm" action="<?php echo site_url('modal_send_sms/sms_form'); ?>" class="form-horizontal" role="form" method="post">
                   <div class="form-group">
                       <label class="col-sm-2 control-label">Sender</label>
                       <div class="col-sm-10">
                           <p class="form-control-static"><label class="label label-primary">Inclusion</label></p>
                       </div>
                   </div>
                   <div class="form-group">
                       <label for="recepients" class="col-sm-2 control-label">To</label>
                       <div class="col-sm-10">
                           <input class="form-control" id="recepients" type="text" placeholder="" name="recepients" >
                           <p class="help-block">
                               <small>
                                   Enter name of person/group in address-book E.g John, Family, Workmates
                               </small>
                           </p>
                       </div>
                   </div>
                   <div class="form-group">
                       <label for="message" class="col-sm-2 control-label">Message</label>
                       <div class="col-sm-10">
                           <textarea class="form-control" name="body" rows="3"></textarea>
                       </div>
                   </div>


                   <a data-toggle="collapse" data-parent="#accordion" href="#SendSMSOptions">
                       <span class="glyphicon glyphicon-plus"></span> Options
                   </a>
                   <div id="SendSMSOptions" class="panel-collapse collapse in">
                       <div class="panel-body">
                           <div class="form-group">
                               <label for="recepients" class="col-sm-2 control-label">Schedule Send</label>
                               <div class="col-sm-10">
                                   <br />
                                   <div class="input-group date">
                                       <input data-provide="datepicker" name="datepicker" type="text" class="form-control"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
                                   </div>
                                   <div class="input-group bootstrap-timepicker">
                                       <input id="timepicker" data-template="modal"  name="timepicker" type="text" class="form-control">
                                       <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                                   </div>
                               </div>
                           </div>
                       </div>
                   </div>

               </form>
           </div>
           <div class="modal-footer">
               <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
               <button type="button" class="btn btn-primary" id="SendSMS">Send Now</button>
           </div>
       </div>
   </div>
</div>

<script>
   $(document).ready(function() {
       $('.collapse').collapse();
       $('#timepicker').timepicker({showMeridian: false, minuteStep: 15, defaultTime: 'current'});

       $('.input-group.date').datepicker({
           format: 'mm/dd/yyyy',
           startDate: '-3d',
           autoclose: true,
           todayHighlight: true
       });


       $("#SendSMS").click(function() {
           event.preventDefault();
           //console.log($('#SendSMSForm').serializeArray());
           var data = $('#SendSMSForm').serializeArray();

           $.post("<?php echo base_url('messages/send') ?>", $('#SendSMSForm').serializeArray())
                   .done(function(data) {
                       alert("Data Loaded: " + data);
                   });


       });
       var cities = new Bloodhound({
           datumTokenizer: Bloodhound.tokenizers.obj.whitespace('text'),
           queryTokenizer: Bloodhound.tokenizers.whitespace,
           prefetch: '<?php echo base_url("c_contacts/index/cities") ?>'
       });
       cities.initialize();

       var elt = $('#recepients');
       elt.tagsinput({
           tagClass: function(item) {
               switch (item.continent) {
                   case 'Europe'   :
                       return 'label label-primary';
                   case 'America'  :
                       return 'label label-danger label-important';
                   case 'Australia':
                       return 'label label-success';
                   case 'Africa'   :
                       return 'label label-default';
                   case 'Asia'     :
                       return 'label label-warning';
               }
           },
           itemValue: 'value',
           itemText: 'text'
       });
       /*
       elt.tagsinput('add', {"value": 1, "text": "Amsterdam", "continent": "Europe"});
       elt.tagsinput('add', {"value": 4, "text": "Washington", "continent": "America"});
       elt.tagsinput('add', {"value": 7, "text": "Sydney", "continent": "Australia"});
       elt.tagsinput('add', {"value": 10, "text": "Beijing", "continent": "Asia"});
       elt.tagsinput('add', {"value": 13, "text": "Cairo", "continent": "Africa"});

       */

       elt.tagsinput('input').typeahead(null, {
           name: 'cities',
           displayKey: 'text',
           source: cities.ttAdapter()
       }).bind('typeahead:selected', $.proxy(function(obj, datum) {
           this.tagsinput('add', datum);
           this.tagsinput('input').typeahead('val', '');
       }, elt));




   });
</script>



RE: facing problems with inserting data - Wouter60 - 02-10-2018

Temporarily, put these lines of code right before $this->sms->savesms($save) in your controller:

PHP Code:
echo '<pre>'
print_r($save);
echo 
'</pre>';
die(); 

Check the value of the variables that are passed in the $save array.
Maybe you'll have to perform a date-time conversion to get the proper format before inserting the data into MySQL.


RE: facing problems with inserting data - dave friend - 02-10-2018

The first question to answer relates to the following

PHP Code:
  function insert_data() {
      $this->db->insert('sms_log'$data);
      $smsid $this->db->insert_id();
  }
  return $smsid

I'll assume that the return statement outside of the function body is a typo.
So the question is, "Where does the $data in $this->db->insert('sms_log', $data); come from?


RE: facing problems with inserting data - gabrielcastillo - 02-10-2018

I agree with dave

Your model should look like this from what I can see.

PHP Code:
<?php defined'BASEPATH' ) OR die('No direct script access allowed!');

class 
sms extends CI_Model {

 
   function insert_data$data ) {
 
       if $this->db->insert('sms_log'$data) ) {
 
           return $this->db->insert_id();
 
       } else {
 
           return FALSE;
 
       }
 
   }
}

/* End of file sms.php */ 

The controller

PHP Code:
<?php defined'BASEPATH' ) OR die('No direct script access allowed!');

class 
sms extends CI_Controller {

 
   public function __construct() {
 
       parent::__construct();
 
       $this->config->load('facebook');
 
       $this->load->library('form_validaiton');
 
       $this->load->library('encrypt');
 
       $this->load->model('countries');
 
       $this->load->model('users');
 
       $this->load->model('sms');

 
   }
 
   public function index() {
 
       $this->load->view('modal_send_sms');
 
   }

 
   public function sms_form(){
 
       $save = array(
 
               'sender'            =>$this->input->post('sender');
 
               'recepients'        =>$this->input->post('recepients');
 
               'body'              =>$this->input->post('body');
 
               'sendscheduletime'  =>$this->input->post('sendscheduletime');
 
       )
 
       
        if 
$this->sms->savesms($save) ) {
 
           redirect('modal_send_sms');
 
       } else {
 
           //Show Error.
 
       }
 
   }
}

/* End of file sms.php */   



RE: facing problems with inserting data - CharlesK - 02-11-2018

Thanks Dave, I think my view is also not working, could you please check it out. Like how i echo the form, because nothing happens when i click the button. Please check it out


RE: facing problems with inserting data - CharlesK - 02-11-2018

Sorry it should be $save


RE: facing problems with inserting data - dave friend - 02-11-2018

The $save array has syntax problems. All the items in the array have semi-colons which should be replaced with commas.

It should be

PHP Code:
$save = array(
 
   'sender'           => $this->input->post('sender'),
 
   'recepients'       => $this->input->post('recepients'),
 
   'body'             => $this->input->post('body'),
 
   'sendscheduletime' => $this->input->post('sendscheduletime'),
); 

Not that it will affect the outcome, but you should consider using base_url() the same way you use site_url(). Use the URI strings as an argument. In other words

PHP Code:
<link href="<?php echo base_url() ?>assets/css/bootstrap-timepicker.min.css" rel="stylesheet"

should be

PHP Code:
<link href="<?php echo base_url('assets/css/bootstrap-timepicker.min.css'); ?>" rel="stylesheet"

Admittedly, this is more of a style than a functional suggestion.

I'm not seeing anything obviously wrong with the view html. I have a suggestion and a question about the button click JavaScript.

I suggest changing the name of the var that holds the return from serializeArray() mostly so it will have a different name than what done(data) uses. Also you don't need to call  serializeArray()  again to set the data for $.post. Then the event handler looks like this

Code:
$("#SendSMS").click(function () {
   event.preventDefault();
   var postData = $('#SendSMSForm').serializeArray();

   $.post("<?php echo base_url('messages/send') ?>", postData)
           .done(function (data) {
               alert("Data Loaded: " + data);
           });
});

My question is: What does 'messages/send' code look like? You didn't show us a "Messages" controller or any methods call send().


RE: facing problems with inserting data - CharlesK - 02-11-2018

Hello dave, here is the messages models,the first one deals with the current insertion am trying to make the second one ads to it though in a different view , I will share with you the code though
Code:
<?php

/*
* Messages class meant to manage interactions between app interface/API & db
*
* @author Codeklerk
*/

class messages extends CI_Model {
   /*
    * Attributes of a message to be sent
     ===================================
    * $type -  of message [email,message,broadcast]
    * $to   - Recepient(s) of the message
    * $from - sender of the message. [default - 'inclusionsms', <custom text>]
    * $scheduledsendtime - $time scheduled for send. [now() or later ()]
    * $mode - mode of sending. [ default via inclusionsms web , <custom modes>]
    *
    * Process gather message details. send to model for persisting
    */

   public $type;
   public $to;
   public $from;
   public $scheduledsendtime;
   public $mode;

   function __construct() {
       parent::__construct();
   }

   function send() {
       // Compile the message here and save to db
       print_r($_POST);
//        $this->sendMessage($to);
   }

   function logMsg() {
       
   }

   function sendMessage($message) {
       
   }

}

Code:
<?php

/*
* Model for an Messages
*/

class message_model extends CI_Model {

   public $message = '';
   public $messageType = '';
   public $messageTo = '';
   public $messageFrom = '';

   function __construct() {
       // Call the Model constructor
       parent::__construct();
   }

   function get_all() {
       $query = $this->db->get('countries');
       return $query->result();
   }

   function get_user_outbox_sms($user) {

       $this->db->select('*');
       $this->db->from('smslog');
       $this->db->join('smslogdetails', 'smslogdetails.logid = smslog.smsid');
       $this->db->where('smslog.sender', $user);
       $this->db->limit(1325);
       $query = $this->db->get();

       return $query->result();
   }

   function sendsms() {
       /*
        * ---- Order of events ----
        * 1.  Save messages
        * 2.  Send SMS, email messages
        * 2.  Log events
        */
   }

   function send_sms($sms_details) {

       $this->db->insert_batch('smslogdetails', $sms_details['send_details']);
   }

   function get_paginated_spaces($start, $limit) {
       $query = $this->db->query('SELECT * FROM  `space`  WHERE  `is_active` =  \'1\' ORDER BY  `space`.`date_posted` DESC LIMIT ' . $start . ' , ' . $limit . ' ');
       return $query->result();
   }

// to adopt function for updating event data
   function update_entry() {
       $this->title = $_POST['title'];
       $this->content = $_POST['content'];
       $this->date = time();
       $this->db->update('entries', $this, array('id' => $_POST['id']));
   }

}

?>



RE: facing problems with inserting data - dave friend - 02-11-2018

The problem is that you cannot direct an ajax request to a model. Any CodeIgniter http: request must be to a controller.

PHP Code:
$.post("<?php echo base_url('messages/send') ?>"postData

Is trying to deliver $_POST data to the method "send" of the controller "Messages". But "Messages" isn't a controller. You'll need to make the call to a controller and have that make the call to the model.


RE: facing problems with inserting data - CharlesK - 02-12-2018

Ooh yeah i get that dave, i will work on, The problem i am seriously facing is the insertion of data in the database as that button does not work at all. Please help me with that. In the modal_send_sms view. I changed the script to look like this:
Code:
<script>
   $(document).ready(function() {
       $('.collapse').collapse();
       $('#timepicker').timepicker({showMeridian: false, minuteStep: 15, defaultTime: 'current'});

       $('.input-group.date').datepicker({
           format: 'mm/dd/yyyy',
           startDate: '-3d',
           autoclose: true,
           todayHighlight: true
       });


                  $("#SendSMS").click(function () {
              event.preventDefault();
              var postData = $('#SendSMSForm').serializeArray();

              $.post("<?php echo base_url('sms/sms_form') ?>", postData)
                      .done(function (data) {
                          alert("Data Loaded: " + data);
                      });
           });


       var cities = new Bloodhound({
           datumTokenizer: Bloodhound.tokenizers.obj.whitespace('text'),
           queryTokenizer: Bloodhound.tokenizers.whitespace,
           prefetch: '<?php echo base_url("c_contacts/index/cities") ?>'
       });
       cities.initialize();

       var elt = $('#recepients');
       elt.tagsinput({
           tagClass: function(item) {
               switch (item.continent) {
                   case 'Europe'   :
                       return 'label label-primary';
                   case 'America'  :
                       return 'label label-danger label-important';
                   case 'Australia':
                       return 'label label-success';
                   case 'Africa'   :
                       return 'label label-default';
                   case 'Asia'     :
                       return 'label label-warning';
               }
           },
           itemValue: 'value',
           itemText: 'text'
       });
       /*
       elt.tagsinput('add', {"value": 1, "text": "Amsterdam", "continent": "Europe"});
       elt.tagsinput('add', {"value": 4, "text": "Washington", "continent": "America"});
       elt.tagsinput('add', {"value": 7, "text": "Sydney", "continent": "Australia"});
       elt.tagsinput('add', {"value": 10, "text": "Beijing", "continent": "Asia"});
       elt.tagsinput('add', {"value": 13, "text": "Cairo", "continent": "Africa"});

       */

       elt.tagsinput('input').typeahead(null, {
           name: 'cities',
           displayKey: 'text',
           source: cities.ttAdapter()
       }).bind('typeahead:selected', $.proxy(function(obj, datum) {
           this.tagsinput('add', datum);
           this.tagsinput('input').typeahead('val', '');
       }, elt));




   });
</script>
The sms is a controller, sms_form is the function