Codeigniter Submit multiple rows in database - codeigniter

I'm trying to submit multiple rows in database. And I'm getting this error:
Filename: C:/xampp/htdocs/soluforma_ghm/system/database/DB_query_builder.php
Line Number: 1481
Can you please share some indications to solve my problem.
Thanks in advance.
My view file with AJAX Append. This way I'm adding multiple inputs
// Add options
$.each(response,function(index,data){
$('#sel_depart').append(
'<div class="form-check">'+
'<input type="checkbox" name="formandos_servicos[]" value="'+data['id']+'">'+
'<input type="text" name="nome_funcionario_servicos[]" value="'+data['title']+'" >'+
'<input type="text" name="naturalidade_servicos[]" value="'+data['naturalidade']+'" placeholder="Naturalidade">'+
'<input type="text" name="data_nascimento_servicos[]" value="'+data['data_nascimento']+'" placeholder="Data Nascimento">'+
'<input type="text" name="nacionalidade_servicos[]" value="'+data['nacionalidade']+'" placeholder="Nacionalidade">'+
'<input type="text" name="doc_identificacao_servicos[]" value="'+data['doc_identificacao']+'" placeholder="Documento de Identificacão">'+
'<input type="text" name="validade_identificacao_servicos[]" value="'+data['validade_identificacao']+'" placeholder="Validade CC">'+
'</div>'
);
}
MY Servicos_model. I'm counting $this->input->post['formandos_servicos'] and submit multiple rows.
public function set_servicos($id = 0) {
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array();
$count = count($this->input->post['formandos_servicos']);
for($i = 0; $i < $count; $i++) {
$data[] = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'area_servicos' => $this->input->post('area_servicos'),
'formadores_servicos' => $this->input->post('formadores_servicos'),
'data_servicos' => $this->input->post('data_servicos'),
'nome_servicos' => $this->input->post('nome_servicos'),
'horas_servicos' => $this->input->post('horas_servicos'),
'conteudos_servicos' => $this->input->post('conteudos_servicos'),
'formandos_servicos' => $this->input->post['formandos_servicos'][$i],
'nome_funcionario_servicos' => $this->input->post['nome_funcionario_servicos'][$i],
'naturalidade_servicos' => $this->input->post['naturalidade_servicos'][$i],
'data_nascimento_servicos' => $this->input->post['data_nascimento_servicos'][$i],
'nacionalidade_servicos' => $this->input->post['nacionalidade_servicos'][$i],
'doc_identificacao_servicos' => $this->input->post['doc_identificacao_servicos'][$i],
'validade_identificacao_servicos' => $this->input->post['validade_identificacao_servicos'][$i],
'anotacoes_servicos' => $this->input->post('anotacoes_servicos'),
'categoria_servicos' => $this->input->post('categoria_servicos'),
'visivel_servicos' => $this->input->post('visivel_servicos'),
'utilizador_servicos' => $this->input->post('utilizador_servicos'),
'criado_servicos' => $this->input->post('criado_servicos'),
'modificado_servicos' => $this->input->post('modificado_servicos')
);
}
if ($id == 0) {
return $this->db->insert_batch('servicos', $data);
}
}

You can Use $this->db->last_query(); to know what's query execute to inserted data in database.
with echo()

Thank you for the reply.
I try print_r to check Array data and I get and empty Array
if ($id == 0) {
//return $this->db->insert_batch('servicos', $data);
echo '<pre>';
print_r($data);
echo '</pre>';
die();
}
print_r Result:
Array
(
)

The Array is now working.
I replace [] with () on
$this->input->post[''][$i]
$this->input->post('')[$i]
On [formandos_servicos] => 972, the Array index is correct.
But are incorrect on:
[nome_funcionario_servicos] => Manuel Fonseca Santos
[naturalidade_servicos] => Fornos Algodres
[data_nascimento_servicos] => 1960-11-15
[nacionalidade_servicos] => Portuguesa
[doc_identificacao_servicos] => 1524575 7ZY0
[validade_identificacao_servicos] => 2019-09-04
because I'm counting:
count($this->input->post('formandos_servicos'));
I'm getting a mismatch between input type="checkbox" and the others input type="text" fields.

Related

how to form popup model validation in codeigniter without using javascript

how to form popup model validation in codeigniter without using javascript and jquery
public function login() {
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[4]|max_length[40]');
if ($this->form_validation->run() && $this->Login_model->loginn($email, $password)) {
$this->welcome();
} else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
$this->index();
}
}
view page, how to form popup model validation in codeigniter without using javascript and jquery
<form id="register-form" onsubmit ="return validateForm()" action="<?php echo base_url(); ?>Index.php/Login_cntrl/login" method="POST" >
<div class="field-wrap">
<label class="view-label">Email Address</label>
<input type="email" placeholder="Email Address" name="email" id="email" class="input-control" value=""/>
</div>
<div class="field-wrap">
<input type="password" placeholder="Password" name="password" id="password" value="" />
<a href="javascript:void(0)" class="btn btn-link btn-nobg" id="btn-show-forgot" >Forgot ?</a>
</div>
<div class="field-wrap">
<button type="submit" class="btn btn-submit" name="ulogin" id="ulogin" value="ulogin" >Login</button>
</div>
<div class="field-wrap">
NEW User? Sign up
</div>
</form>
model code,how to form popup model validation in codeigniter without using javascript and jquery
public function loginn($email, $password) {
// $this->db->where('email', $email);
$where="(email='$email' or mobile_no='$email') and password='$password'";
$this->db->where($where);
$query = $this->db->get('customer_registration');
$count = $query->num_rows(); //counting result from query
if ($count === 0) {
// $this->db->where('email', $email);
$where="(email='$email' or mobile_no='$email') and password='$password'";
$this->db->where($where);
// $this->db->where('password', $password);
$query = $this->db->get('supplier_registration');
}
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
//add all data to session
$newdata = array(
'id' => $row->id,
'first_name' => $row->first_name,
'last_name' => $row->last_name,
'email' => $row->email,
'password' => $row->password,
'mobile_number' => $row->mobile_number,
'logged_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return true;
}
return false;
}
Below shown code is working properly
public function loginn($email, $password) {
// $this->db->where('email', $email);
$where = "(email='$email' or mobile_no='$email') and password='$password'";
$this->db->where($where);
$query = $this->db->get('customer_registration');
$count = $query->num_rows(); //counting result from query
$tablename = "customer";
if ($count === 0) {
// $this->db->where('email', $email);
$where = "(email='$email' or mobile_no='$email') and password='$password'";
$this->db->where($where);
// $this->db->where('password', $password);
$query = $this->db->get('supplier_registration');
$tablename = "supplier";
}
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
//add all data to session
$newdata = array(
'id' => $row->id,
'first_name' => $row->first_name,
'last_name' => $row->last_name,
'email' => $row->email,
'password' => $row->password,
'mobile_number' => $row->mobile_number,
'log_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return $tablename;
}
return $tablenam = " '";
}

codeigniter login validation not validating rules

am using codeigniter 3.0.4 .here this Here the action send to the controler(first.php)not validating anything it will turn to else statement and display login page again(as set as in redirect('welcome/login_page');). my register function in the same controller working good. what is the exact problem ..please help me to find it.thanks.
..............the controller(first.php).....
public function signup_validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|valid_email|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'required|md5|trim');
if($this->form_validation->run() ){
$user_id= $this->model_users->get_id($this->input->post('email'));
$user_status = $this->model_users->get_status($this->input->post('email'));
$data = array (
'user_id' => $user_id,
'email' => $this->input->post('email'),
'user_status' =>$user_status,
'is_logged_in' => 1
);
$this->session->set_userdata($data);
}
if ($this->session->userdata('user_status')=='0') {
redirect('main/admins');
}
elseif ($this->session->userdata('user_status')=='1') {
redirect('main/members');
}else{
redirect('welcome/login_page');
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in() ){
return TRUE;
} else {
$this->form_validation->set_message('validate_credentials', 'Invalid useername(email-id) or password. !');
return FALSE;
}
}
....the view(login.php)......
echo form_open("first/signup_validation");
echo'<div class="row">';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="email">Email<span></span></label>';
echo'<input type="text" class="form-control" id="email">';
echo'</div>';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="password">Password<span></span></label>';
echo'<input type="password" class="form-control" id="password">';
echo'</div>';
echo'</div>';
$data2 = array(
'class' => 'btn btn-default',
);
echo form_submit($data2, 'Login');
echo form_close('');
?>
echo '<input type="text" class="form-control" id="email">';
Your input elements don't contain a name attribute. The name is what's used as the identifier in the validation rule.
$this->form_validation->set_rules('email'... // <- 'email' is the name attribute
Do this...
echo'<input type="text" class="form-control" id="email" name="email">';

How can i insert multiple arrays into mysql database using codeginiter?

What i want is, i have a uniq id call num i want insert mutiple description for that unique num. i have a form to add fileds dynamically so i can add fields as much i want. when i try to insert one row data its works perfectly when i try to insert more than one row data it doesn't work.
My View page :
<form name="codexworld_frm" action="" method="post">
<div class="field_wrapper">
<input type="text" name="num" value=""/><br />
<input type="text" name="description[]" value=""/><input type="text" name="voucher_no[]" value=""/><input type="text" name="price[]" value=""/>
<img src="<?php echo base_url('images/add-icon.png'); ?>"/>
</div>
<input type="submit" name="submit" value="SUBMIT"/>
</form>
My Controller :
$data = array(
'no' => $this->input->post('num'),
'descriptions' => $this->input->post('description'),
'voucher' => $this->input->post('voucher_no'),
'des_price' => $this->input->post('price'),
);
$this->multi_model->form_insert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('multi_view', $data);
My Model:
function form_insert($data){
$this->db->insert('tbl_description', $data);
}
if i use foreache loop into my model i think it will work but i how do i use ?
When i use print_r() function this is out put
1001
Array
(
[0] => description1
[1] => description2
[2] => description3
)
Array
(
[0] => voucher 1
[1] => voucher 2
[2] => voucher 3
)
Array
(
[0] => 100
[1] => 200
[2] => 300
)
see this link it is use multiple insert without loop or you can use your foreach loop in controller count description post and go through it.
$data = array();
$count = count($this->input->post['description']);
for($i=0; $i < $count; $i++) {
$data[] = array(
'no'=>$this->input->post('num'),
'descriptions' => $this->input->post['descriptions'][$i],
'voucher' => $this->input->post['voucher'][$i],
'des_price' => $this->input->post['des_price'][$i],
);
}
$this->db->insert_batch('tbl_description', $data);
Hope this will helps you..
Controller
//if voucher_no is required..
$voucher_no = $this->input->post('voucher_no');
$count = count($voucher_no);
if ($count > 0) {
for ($i = 0; $i < $count; $i++) {
if (!empty($voucher_no[$i])) {
$data = array(
'no' => $this->input->post('num'),
'descriptions' => $this->input->post('description')[$i],
'voucher' => $this->input->post('voucher_no')[$i],
'des_price' => $this->input->post('price')[$i],
);
$this->multi_model->form_insert($data);
}
}
}
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('multi_view', $data);
Let us know the results..
change model as following.
function form_insert($data){
foreach($data['description'] as $key=>$des)
{
$savedata = array(
'no' => $data('no'),
'descriptions' => $des,
'voucher' => $data['voucher'][$key],
'des_price' => $data['dec_price'][$key],
);
$this->db->insert('tbl_description', $savedata);
}
}
you can insert object wise.
in your controller:-
$value=$this->input->post('num');
$count=count($val);
for($i=0; $i<$count; $i++){
$data['no']=$this->input->post('num')[$i];
$data['description']=$this->input->post('description')[$i];
$data['voucher']=$this->input->post('voucher')[$i];
$data['prize']=$this->input->post('prize')[$i];
$this->multi_model->form_insert($data);
}

CakePHP Js Helper - Update 3 Dropdown menus dynamically

i'm using CakePHP 2.6.1
I have a cakephp form to handle accesses with these 3 dropdown menues:
location->facility->department
I want them to be dynamic populated and so i followed this tutorial http://marnienickelson.com/2014/10/11/dynamic-dropdowns-with-cakephp-2-x/
It works well, except one little problem. If i change the "location", the "facility" Dropdown menu is filled correctly, but the "department" menu stays blank...
My AccessesController.php
public function add() {
if ($this->request->is('post')) {
$this->Access->create();
if ($this->Access->save($this->request->data)) {
$this->Session->setFlash(__('The access has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The access could not be saved. Please, try again.'));
}
}
$titles = $this->Access->Title->find('list');
$locations = $this->Access->Facility->Location->find('list');
$systems = $this->Access->System->find('list');
$this->set(compact('titles', 'locations', 'facilities', 'departments', 'systems'));
}
My get_by_location.ctp (and i have an equal file called get_by_facility.ctp)
<?php foreach ($facilities as $key => $value): ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php endforeach; ?>
And at the end of my add.ctp
<?php
$this->Js->get('#AccessLocationId')->event('change',
$this->Js->request(array(
'controller'=>'facilities',
'action'=>'getByLocation'
), array(
'update'=>'#AccessFacilityId',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
$this->Js->get('#AccessFacilityId')->event('change',
$this->Js->request(array(
'controller'=>'departments',
'action'=>'getByFacility'
), array(
'update'=>'#AccessDepartmentId',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
?>
I know the second event'change' isnt recognized and thats why my 3rd dropdown stays blank... Is there an other event then 'change'? Or could i put these two ajax requests in one?
This Blog helped me alot Euromarks blog
I just changed my get_by_location.ctp file:
<?php
if (!empty($facilities)) {
echo '<option value="">' . __('pleaseSelect') . '</option>';
foreach ($facilities as $k => $v) {
echo '<option value="' . $k . '">' . h($v) . '</option>';
}
} else {
echo '<option value="0">' . __('noOptionAvailable') . '</option>';
}
So if first dropdown is changed, the second one will display "please select".

Laravel. Controller not getting the values from the Form

The controller is not getting the data from the FORM. I realise that the Form has by default a Post method, while the Route is using a Get, but if I change that, then the form will not display the form fields. Validation fails as the "required" does not get any values, so it returns to the same page. If I remove the validation filter, then it does go to the results page, but all it does is show ALL of the content of the table, since it is getting no parameters (where) from the Form. The weird thing is that in the past, it worked, but I must have messed up with some part of the code and now it doesn't. To save space here I have left out many fields which dont play a role in the problem.
The Form has three interdependent Fields Country, Region and Town, which are filled up alright.
FORM:
<form action = "{{URL::route('sacapropiedades')}} "class="form-horizontal" id="my_form" name="my_form">
<div class="form-group">
<div class="col-sm-3">
<label for="country">Pays</label>
<select name ="country" {{ (Input::old('country')) ?' value ="' . e(Input::old('country')). '"' : '' }} id = "country" class="form-control">
#foreach($countries as $country)
<option value="{{$country->country}}">{{$country->country}}</option>
#endforeach
</select>
</div>
<div class="col-sm-3">
<label for="town">Ville</label>
<select name ="town" {{ (Input::old('town')) ?' value ="' . e(Input::old('town')). '"' : '' }}id = "town" class="form-control">
</select>
</div>
</div><!-- END OF THIRD FORMGROUP -->
<div class="form-group">
<div class="col-sm-4">
</div>
<div class="col-sm-2">
<button type="submit" class="btn btn-success">Enviar</button>
<button type="reset" class="btn btn-danger">Borrar</button>
</div>
</div>
</form>
ROUTES
Route::get('realestate/listproperty', array(
'as' =>'sacapropiedades',
'uses' =>'countriesregionstownsController#findproperty'
));
CONTROLLER
public function findproperty(){
/*IT REPEATS THE COUNTRY QUERY ABOVE BECAUSE IT IS GOING TO USE IT
*ON THE RESULTS PAGE AND IT GIVES THE USER TO SELECT AGAIN OTHER COUNTRIES
*WITHOUT HAVING TO RETURN TO THE FIRST PAST PAGE*/
$countries = DB::table('properties')
->select('country')
->distinct()
->get();
/*FIRST VALIDATE INPUT DATA*/
$validator = Validator::make(Input::all(),
array(
'country' =>'required',
'regions' =>'required',
'transaction' =>'required',
'town' =>'required'
));
if($validator->fails()){
return Redirect::route('showrealestate')
->withErrors($validator)
->withInput();
}
else{
$country = Input::get('country');
$region = Input::get('regions');
$town = Input::get('town');
$transaction = Input::get('transaction');
$pricefrom = Input::get('pricefrom');
$priceto = Input::get('priceto');
$roomsfrom = Input::get('roomsfrom');
$roomsto = Input::get('roomsto');
$builtyear = Input::get('builtyear');
$swimming = Input::get('swimming');
$garden = Input::get('garden');
$garage = Input::get('garage');
$message = Input::get('message');
}
$country = DB::table('countries')->where('id_pais', $country)->pluck('nombre_pais');
$region = DB::table('regions')->where('id_region', $region)->pluck('nombre_region');
$town = DB::table('cities')->where('id_localidad', $town)->pluck('nombre_localidad');
$users = DB::table('users')
->join('properties', 'users.id', '=', 'properties.id_user_fk')
->select('users.email', 'properties.id_user_fk', 'properties.country', 'properties.region', 'properties.town',
'properties.price', 'properties.rooms','properties.m2','properties.swimming',
'properties.garden','properties.garage','properties.builtyear','properties.message',
'properties.pic1',
'properties.pic2', 'properties.pic3','properties.pic4','properties.pic5','properties.pic6');
if (!empty($country)) {
$users = $users->where('country', '=', $country);
}
if (!empty($region)) {
$users = $users->where('region', '=', $region);
}
if (!empty($town)) {
$users = $users->where('town', '=', $town);
}
if (!empty($transaction)) {
$users = $users->where('transaction', '=', $transaction);
}
if (!empty($pricefrom)) {
$users = $users->where('price', '>', $pricefrom);
}
if (!empty($priceto)) {
$users = $users->where('price', '<', $priceto);
}
if (!empty($roomsfrom)) {
$users = $users->where('rooms', '>', $roomsfrom);
}
if (!empty($roomsto)) {
$users = $users->where('rooms', '<', $roomsto);
}
if (!empty($builtyear)) {
$users = $users->where('builtyear', '>', $builtyear);
}
if (!empty($swimming)) {
$users = $users->where('swimming', '=', $swimming);
}
if (!empty($garage)) {
$users = $users->where('garage', '=', $garage);
}
if (!empty($garden)) {
$users = $users->where('garden', '=', $garden);
}
if (!empty($message)) {
$users = $users->where('message', '=', $message);
}
$users = $users->get();
return View::make('realestate.externa.listproperty', compact('users','countries'));
}
A post method is mandatory, otherwise Laravel will not redirect it to the correct method with the correct data. How was it working before? By luck, probably. :)
Route::get('realestate/listproperty', array(
'as' =>'sacapropiedades',
'uses' =>'countriesregionstownsController#findproperty'
));
Route::post('realestate/listproperty', array(
'as' =>'sacapropiedades',
'uses' =>'countriesregionstownsController#findproperty'
));
or
Route::match(array('GET', 'POST'), 'realestate/listproperty', array(
'as' =>'sacapropiedades',
'uses' =>'countriesregionstownsController#findproperty'
));
or
Route::any('realestate/listproperty', array(
'as' =>'sacapropiedades',
'uses' =>'countriesregionstownsController#findproperty'
));
Then you'll probably need to not validate on GET:
if (Request::getMethod() == 'POST')
{
$validator = Validator::...
}
EDIT:
Sorry I overlooked this problem:
Instead of writing your FORM tag manually, use Laravel's FormBuilder class:
<?php Form::open(array('route' => 'sacapropiedades', 'class' => 'form-horizontal', 'id' => 'my_form', 'name' => 'my_form')); ?>
The difference is that it will add the method for you and it will also add a csrf token to your form.

Resources