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

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

Related

How to insert into database 3 arrays files on 3 field

i have a problem in my try project on upload multiple image.
I can't just use a fixed number of file to upload. I tried many many solutions on StackOverflow but I wasn't able to find a working one..
my table format on database :
enter image description here
Here's my Upload controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Upload2 extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('url','html','form'));
$this->load->model('m_upload');
}
function index(){
$this->load->view('upload_form');
}
function upload() {
if($this->input->post('upload'))
{
$foto = array();
$number_of_files = sizeof($_FILES['userfiles']['tmp_name']);
$files = $_FILES['userfiles'];
$config=array(
'upload_path' => './uploads/', //direktori untuk menyimpan gambar
'allowed_types' => 'jpg|jpeg|png|gif',
'max_size' => '2000',
'max_width' => '2000',
'max_height' => '2000'
);
for ($i = 0;$i < $number_of_files; $i++)
{
$_FILES['userfile']['name'] = $files['name'][$i];
$_FILES['userfile']['type'] = $files['type'][$i];
$_FILES['userfile']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['userfile']['error'] = $files['error'][$i];
$_FILES['userfile']['size'] = $files['size'][$i];
$this->load->library('upload', $config);
$this->upload->do_upload('userfile');
$foto[] = $this->upload->data();
$data = array(
//$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;
'foto' => $foto[0]['file_name'],
'foto_ktp' => $foto[1]['file_name'],
'foto_npwp' => $foto[2]['file_name']
);
//$this->m_upload->m_upload($data);
$result_set = $this->m_upload->insert($data);
}
}
$this->load->view('upload_success');
}
}
My upload form is This.
<!DOCTYPE html>
<html>
<head>
<title>Tutorial CodeIgniter with Gun Gun Priatna</title>
</head>
<body>
<h2>Upload Gambar</h2>
<?php echo form_open_multipart('index.php/upload2/upload'); ?>
<table>
<tr>
<td>FILE 1<input type="file" name="userfiles[0]" /></td>
<td>FILE 2<input type="file" name="userfiles[1]" /></td>
<td>FILE 3<input type="file" name="userfiles[2]" /></td>
</tr>
<tr>
<td><input type="submit" name="upload" value="upload"></td>
</tr>
</table>
<?php echo form_close();?>
</body>
</html>
how to fix insert 3 file into database above..thank u very much..
You are inserting in the loop, you want to insert after the loop when you have all the files.
PHP:
function upload() {
if (!empty($_FILES['userfiles']['name'])) {
$foto = array();
$number_of_files = count($_FILES['userfiles']['tmp_name']);
$files = $_FILES['userfiles'];
$config = array(
'upload_path' => './uploads/', //direktori untuk menyimpan gambar
'allowed_types' => 'jpg|jpeg|png|gif',
'max_size' => '2000',
'max_width' => '2000',
'max_height' => '2000'
);
$this->load->library('upload', $config);
$foto = array();
for ($i = 0; $i < $number_of_files; $i++) {
$_FILES['userfile']['name'] = $files['name'][$i];
$_FILES['userfile']['type'] = $files['type'][$i];
$_FILES['userfile']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['userfile']['error'] = $files['error'][$i];
$_FILES['userfile']['size'] = $files['size'][$i];
if (!$this->upload->do_upload('userfile')) {
show_error($this->upload->display_errors());
}
$foto[] = $this->upload->data('file_name');
}
$data = array(
'foto' => $foto[0],
'foto_ktp' => $foto[1],
'foto_npwp' => $foto[2]
);
$this->m_upload->insert($data);
$this->load->view('upload_success');
} else {
show_error('No files uploaded!');
}
}
HTML:
No need for userfiles[2] just call them userfiles[]

Codeigniter Submit multiple rows in database

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.

Clear or reset the wordpress posts pagination while changing filters

I think it is simple, but I don't get it.
This is my filter:
<form class='post-filters'>
<select name="filter">
<?php
$filter_options = array(
'houses' => 'Houses',
'hotels' => 'Hotels',
);
foreach( $filter_options as $value => $label ) {
echo "<option ".selected( $_GET['filter'], $value )." value='$value'>$label</option>";
}
?>
</select>
<input type='submit' value='Filter!'>
</form>
Related PHP to apply the filter to the wordpress query:
<?php
global $destinations;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$destinations = new WP_Query([
'paged' => $paged,
'location' => $location,
'category_name' => urldecode(get_query_var('filter')),
'posts_per_page' => 6
]);
?>
If I do select my "filter" and the result has more than six entries, I use next_posts_link() to see the next six results. The problem is now, if I'm on page 2 or 3 and the other filter has less than e.g. 6 entries, I will see no results while changing my filter.
How do I clear the get variable (/page/2/) while changing my filter?
Example:
category/subcategory/subsubcategory/page/3/?filter=houses
Now I select "filter" hotels
category/subcategory/subsubcategory/page/3/?filter=hotels
and the "/page/3" will not be cleared. So I can not see some posts.
It has been anwsered here:
https://wordpress.stackexchange.com/a/264266
function get_nopaging_url() {
$current_url = $_SERVER[REQUEST_URI];
$pattern = '/page\\/[0-9]+\\//i';
$nopaging_url = preg_replace($pattern, '', $current_url);
return $nopaging_url;
}
You could use this function to remove the pagination in your urls with filters.
See example:
<a href="<?php echo get_nopaging_url(); ?>?filter=houses">

Saving data from a drop down list in CodeIgniter

I created a menu page where it has a drop down menu with a list of menus from the database and it also has a textbox to enter new menus.
The problem I'm having is that I can't seem to figure out how to save my dropdown. So for example I have a menu called "About Us" in the drop down list and I want to create a new menu called "Team", and "Team" is a child of "About Us"
So in my table I would have something like this
id | parent | title
------------------------
1 | NULL | About Us
2 | 1 | Team
Menu Controller
function get_data_from_post()
{
$data['title'] = $this->input->post('title', TRUE);
$data['parent'] = $this->input->post('parent', TRUE);
if(!isset($data)){
$data = '';
}
return $data;
}
function get_data_from_db($update_id)
{
$query = $this->get_where($update_id);
foreach($query->result() as $row){
$data['title'] = $row->title;
$data['parent'] = $row->parent;
}
return $data;
}
function create()
{
$update_id = $this->uri->segment(3);
$submit = $this->input->post('submit', TRUE);
if($submit == "Submit"){
//person has submitted the form
$data = $this->get_data_from_post();
}else{
if(is_numeric($update_id)){
$data = $this->get_data_from_db($update_id);
}
}
if(!isset($data)){
$data = $this->get_data_from_post();
}
//$titles = array();
$query = $this->get('title');
foreach($query->result() as $row){
$titles[] = $row->title;
}
$data['titles'] = $titles;
$data['update_id'] = $update_id;
$data['view_file'] = "create";
$this->load->module('templates');
$this->templates->admin_template($data);
}
function submit()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required|xss_clean');
if($this->form_validation->run($this) == FALSE){
$this->create();
}else{
$data = $this->get_data_from_post();
$update_id = $this->uri->segment(3);
if(is_numeric($update_id)){
$this->_update($update_id, $data);
}else{
$this->_insert($data);
}
redirect('menus/manage');
}
}
create.php view
<div class="row">
<div class="col-md-12">
<h2>Create Menus</h2>
<h5>Welcome Jhon Deo , Need to make dynamic. </h5>
</div>
</div>
<hr />
<?php
echo validation_errors("<p style='color: red;'>", "</p>");
echo form_open('menus/submit/'.$update_id);
?>
<div class="row">
<div class="col-md-12">
<form role="form">
<div class="form-group">
<select name="menus">
<?php
foreach($titles as $title){
echo "<option value=".$title.">".$title."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label>Title</label>
<!-- <input class="form-control" /> -->
<?php
$data = array(
'name' => 'title',
'id' => 'title',
'value' => $title,
'class' => 'form-control',
);
echo form_input($data);
?>
</div>
<?php
$data = array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Submit',
'class' => 'btn btn-success',
'style' => 'width: 100%',
);
echo form_submit($data);
?>
</form>
</div>
</div>
<?php
echo form_close();
?>
UPDATE:
this is what I have when I print_r($titles)
Array
(
[0] => About Us
[1] => Home
)
If there is anything you don't understand or if you need me to give more information please let me know.
You should have declared a model. From there, you can create a function that will save the values in the database that you initialize via controller. You should utilize the MVC pattern of it. CodeIgniter has a great documentation to read about what I am pointing out.. https://codeigniter.com/user_guide/overview/mvc.html?highlight=model

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