How insert multiple data using array - php

I'm a newbie using php CodeIgniter. I can insert the array using php native. but how I can insert array using CodeIgniter, please? help me
I have a program for many checkboxes. if I checked more than 1 or checked all it's just still insert 1 data. its said success but just 1 data. so I want to insert more than 1. how can I do that's code? please fix it
this is my function order code from the controller :
public function order()
{
$this->form_validation->set_rules('id_sub', 'Id_sub', 'required|trim');
if ($this->form_validation->run() == false) {
$data['title'] = 'Order';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$data["home"] = $this->product_model->getAll_join();
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('user/order', $data);
$this->load->view('templates/footer');
} else {
$data = [
'id_sub' => htmlspecialchars($this->input->post('id_sub', true))
];
$this->db->insert('tbl_order_detail', $data);
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Data berhasil disimpan.
</div>');
redirect('user/order');
}
}
this is my view order code :
<tbody>
<tr>
<td>
<?php
$query = $this->db->query("select tbl_referensi.referensi, tbl_sub_kategori.sub, tbl_sub_kategori.id_sub
from tbl_referensi
inner join tbl_sub_kategori
on tbl_referensi.id_ref = tbl_sub_kategori.id_ref
where tbl_referensi.id_ref = $tampil->id_ref;
");
foreach ($query->result() as $tampil_sub) :
?>
<input type="checkbox" aria-label="Checkbox for following text input" name="id_sub" id="id_sub" value="<?= $tampil_sub->id_sub ?>"> <label for="name" class="mr-4"><?= $tampil_sub->sub ?></label>
<?php endforeach; ?>
</td>
</tr>
</tbody>
i think the problem is from function order and tag HTML(name="id_sub") from view order. maybe using id_sub[].
but how? please fix it and help me.

Use this
<input type="checkbox" aria-label="Checkbox for following text input" name="id_sub[]" id="id_sub" value="<?= $tampil_sub->id_sub ?>"> <label for="name" class="mr-4"><?= $tampil_sub->sub ?></label>
and you will get value in controller using
$post_data = $this->input->post('id_sub');
foreach ($post_data as $key=>$value) {
// do your code
}

Here in html, input name should be an array
<input type="checkbox" aria-label="Checkbox for following text input" name="id_sub[]" id="id_sub" value="<?= $tampil_sub->id_sub ?>"> <label for="name" class="mr-4"><?= $tampil_sub->sub ?>
Mysql Query:
$data = [
'id_sub' => implode(',',$this->input->post('id_sub'))
];
$this->db->insert('tbl_order_detail',$data);

Related

Pass Value From Controller to Model CodeIginter Using Stored Procedure

I have a problem with Codeigniter. I try to pass value from view to controller and it works. But there is a problem when it passing from controller to model. It didn't return any value into View.
Here is my controller:
public function Edit2G() {
$id = $this->uri->segment(3);
$this->load->model("main_model");
$data['fetch_data_2G_where'] = $this->main_model->fetch_data_2G_id($id);
$data['id'] = $id;
$data['title'] = "Update Data 2G";
$this->load->view('templates/header');
$this->load->view("pages/Update2G", $data);
$this->load->view('templates/footer');
}
Here is Model
function fetch_data_2G_id($id)
{
$get_2G_data_stored_proc = "CALL Get_2G_Data(?)";
$data = array( 'id' =>$id);
$query = $this->db->query($get_2G_data_stored_proc, $data);
$result = $query->result_array();
return $get_2G_data_stored_proc;
}
And this is my View
<h2 align="center"><?=$title ?></h2>
<h3 align="center"><?=$id ?></h3>
<p align="center"><?php echo $fetch_data_2G_where['id'];?></p> //This is a test
<?php echo form_open('posts/update'); ?>
<input type="hidden" name="id" value="<?php //echo $fetch_data_2G_where['id']; ?>">
<div class="form-group">
<label>Site ID</label>
<input type="text" class="form-control" name="title" placeholder="add title" value="<?php //echo $fetch_data_2G_where['site_name'];?>">
</div>
This is the stored procedure result
id, id_site, site_name, bsc_name, bcf_id, vlan1, vlan2, status,status_vlan
'1', 'COK008', 'Combat Batylon754','FBTIMIKA-1','BCF-0112', '3677', '3137', '', 'Metro E'
This in Error That I got
A PHP Error was encountered Severity: Warning
Message: Illegal string offset 'id'
Filename: pages/Update2G.php
Line Number: 3
Backtrace:
File: C:\xampp\htdocs\DapotTimika\application\views\pages\Update2G.php
Line: 3 Function: _error_handler
File: C:\xampp\htdocs\DapotTimika\application\controllers\Pages.php
Line: 46 Function: view
File: C:\xampp\htdocs\DapotTimika\index.php Line: 315 Function:
require_once
What I am missing?
PS: the stored procedure only has one parameter (id) to return / get data
in your controller print_r the below line
$data['fetch_data_2G_where'] = $this->main_model->fetch_data_2G_id($id);
echo "<pre>"; print_r($data['fetch_data_2G_where']);
just to see what's the result your query returning. then from your result you can analyse and get the desired results in view.
Thank You Guys for the answer, I found the answer.
I Forgot to parse return value from model into array. The code in model and controller is fine.
here is my view code
<?php
if($fetch_data_2G_where->num_rows() > 0)
{
foreach($fetch_data_2G_where->result_array() as $data)
{
?>
<input type="hidden" name="id" value="<?php echo $data['id']; ?>">
<div class="form-group">
<label>Site ID</label>
<input type="text" class="form-control" name="site_id" value="<?php echo $data['id_site'];?>">
<?php } ?>
Here is the Result

How to get validation errors in codeigniter?

Hello I am inserting data in database. When I insert both category and description then data in inserting but when I don't insert in the category and description input and click on create then no error showing with blank page admin/category/ register_category, I want to show that category and description field should not be empty.
category.php view page is below :
<?php if(isset($_SESSION['success'])){ ?>
<div class="alert alert-success"><?php echo $_SESSION['success']; ?>
</div>
<?php } ?>
<?php echo validation_errors('<div class="alert alert-danger">','</div>'); ?>
<form class="form" action="<?php echo site_url('admin/category/register_category') ?>" method="POST">
<label for="contactinput5">Category Name</label>
<input class="form-control border-primary" type="text" placeholder="category" name="category" id="contactinput5">
<label for="contactinput5">Discription</label>
<textarea class="form-control border-primary" type="text" placeholder="discription" name="discription" id="contactemail5"></textarea>
<button type="submit" name="create" class="btn btn-primary">
and my controller Category.php page is:
<?php
class Category extends CI_Controller {
function index() {
$this->load->view('admin/category');
}
function register_category() {
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if($this->form_validation->run() == TRUE){
echo "form validate";
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category){
$this->session->set_flashdata("success","Your data has been added");
redirect("admin/category","refresh");
}
else{
redirect('admin/category');
}
}
}
}
?>
model categories page:
<?php
class Categories extends CI_Model
{
function validate()
{
$arr['categoryname'] = $this->input->post('category');
$arr['discription'] = $this->input->post('discription');
return $this->db->insert('category',$arr);
}
}
?>
If validation result is not true, you can get errors from $this->form_validation->error_array(), loop the return array and show the error to the user.
Hope this help.
hey guys thanks and i got my answer just by putting this code
if($this->form_validation->run() == FALSE)
{
$this->index();
}
Hello Please update your function in the controller. There is issue in validation condition Changes TURE to FALSE. Check below code.
function register_category()
{
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('category');
}
else
{
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category)
{
$this->session->set_flashdata("success","Your data has been added");
redirect("admin/category","refresh");
}
else
{
redirect('admin/category');
}
}
}
Get all post validation errors in controller :
echo validation_errors();
If you want to show at the end of textbox use this following method :
<label for="contactinput5">Category Name</label>
<input class="form-control border-primary" type="text" placeholder="category" name="category" id="contactinput5">
<?php echo form_error('category', '<div class="error">', '</div>'); ?>
FYI your solution only worked because validation_errors() only applies to the current instance. When you redirect that information is lost. You would have to store it in session variable or this is common (change form action to self or leave blank):
function index() {
if ($_POST) {
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if($this->form_validation->run() == TRUE){
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category){
$this->session->set_flashdata("success","Your data has been added");
}
}
}
$this->load->view('admin/category');
}
Of course your way works too if you are ok with the url changing.

Insert into DB with codeigniter 3

im trying to add new post into my db. I have Model, Controller and View created. Actualy im using rest api for this, but now I want to do it with pure php powerd.
But After form validation is nothing. So when I try to post, nothuing happens.
Here is my code.
Model:
// Create
function create($data) {
// Insert data into DB
$this->db->insert('blog', $data);
return $this->db->insert_id();
}
Controller:
public function add() {
if ($this->ion_auth->is_admin()) {
// Validation rules
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
if (($this->form_validation->run() == FALSE)) {
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
if($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
$this->blog_model->create($data);
redirect(base_url().'blog/');
}
}
} else {
redirect('login');
}
}
And at least my view:
<div class="uk-margin-top">
<?php $attributes = array("class" => "uk-panel uk-panel-box uk-form uk-margin-lage-bottom", "id" => "add-form", "method" => "post");
echo form_open("/backend/blog/add", $attributes); ?>
<div class="uk-form-row">
<label class="uk-form-label" for="title">Title</label>
<input id="title" class="uk-width-1-1 uk-form-large title redactor-box" name="title" placeholder="Beitragstitel" type="text"
value="<?php echo set_value('title'); ?>"/>
<span class="uk-text-danger"><?php echo form_error('title'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="teaser">Teaser</label>
<textarea id="teaser" class="uk-width-1-1 uk-form-large teaser redactor-box" name="teaser" data-uk-htmleditor></textarea>
<span class="uk-text-danger"><?php echo form_error('teaser'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="body">Body</label>
<textarea id="full" name="full" rows="4" placeholder="Ihre Nachricht"
value="<?php echo set_value('full'); ?>"></textarea>
<span class="uk-text-danger"><?php echo form_error('full'); ?></span>
</div>
<div class="uk-form-row">
<a class="uk-button uk-button-success" data-action="add-post">Submit</a>
</div>
<?php echo form_close(); ?>
</div>
So my problem is, when I click on my submit button - nothing. Maybe you can show me where my problem is.
Thank you!
For your controller, I think you are missing the form helper and validation library. I have included other comments in the code, but try this:
public function add() {
// you need to load these in:
$this->load->helper('form');
$this->load->library('form_validation');
// I am assuming ion_auth is working, however, I would try this code without
// this conditional statement
if ($this->ion_auth->is_admin()) {
// Validation rules
// Make sure the second parameter is right. I think Titel should be Title.
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
// added a triple === instead of == for stricter type checking
if (($this->form_validation->run() === FALSE)) {
// I am assuming $this->data is a property of your controller class
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
// Check if the form was submitted via $_POST method
if($this->input->post()) {
// I removed your $data array and created it in the model.
// I added a condition here to check if the data was successfully inserted
if ($this->blog_model->create()) {
redirect(base_url().'blog/');
} else {
// output an error message or redirect
}
}
}
} else {
redirect('login');
}
}
For your model, I think you were not passing any data to your model. Try the following for your model:
public function create()
{
// you need to pass an array of data or an object
// the array key corresponds to your db table column
// the array value corresponds to your views input field names
$data = array(
'name' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
// returns true or false
return $this->db->insert('blog', $data);
}

codeigniter form not submitting data

I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.

CodeIgniter: Populate an input text in the view from data array grabbed from database

This return of print_r($query->result()); would be:
Array ( [0] => stdClass Object ( [guest_name] => Test Name [guest_gender] => Male [guest_nic_pp_dl] => 123456789 ) )
What I need is to pass those values into input text boxes, radio buttons and dropdowns in the view respectilvely.
For example, I need 'guest_name' to be in an input, 'guest_gender' value to be selected on the view, and dropdown value corresponding to 'guest_nic_pp_dl' to be selected on a dropdown (HTML select).
Controller:
function get_customer_details() {
$guest_name = $this->input->post('guest_name');
$this->banquet_model->talk_to_new_guest_table($guest_name);
$this->load->view('/main/banquet_view');
}
Model:
function talk_to_new_guest_table($guest_name) {
$query = $this->db->query(" SELECT guest_name, guest_gender, guest_nic_pp_dl
FROM new_guest
WHERE guest_name LIKE '$guest_name%'
LIMIT 1 ");
if($query->num_rows()>0) {
return $query->result();
}
else {
return 0;
}
}
View:
<div class="control-group">
<label for="guest_name" class="control-label"><i class="icon-user"></i> Name: </label>
<div class="controls">
<div class="input-append">
<input type="text" id="appendedInputButtons" class="span2" name="guest_name" value="<?php echo set_value('guest_name'); ?>">
<input class="btn" type="submit" name="searchGuest" value="Search">
</div>
<?php echo form_error('guest_name'); ?>
</div>
make some changes in
Controller :
$guest=$this->banquet_model->talk_to_new_guest_table($guest_name);
//creating data array from returned result
$data['guest_name']=$guest->guest_name;
$data['guest_gender']=$guest->guest_gender;
$data['guest_nic_pp_dl']=$guest->guest_nic_pp_dl;
//loading view with data
$this->load->view('/main/banquet_view',$data);
more important all these data array element will be available as variable on view page like
$data['guest_gender'] as $guest_gender
The answers from Rajeev Ranjan and Prasanth are ok but on the line return $query->result(); you can do thisreturn $query->row(); the reason is because the result() returns an array of objects which needs to be iterated while the row() object returns a single object which you can reference without iterating with a loop. I hope this will help
Try something on the lines of:
Controller:
function get_customer_details() {
$guest_name = $this->input->post('guest_name');
$data = $this->banquet_model->talk_to_new_guest_table($guest_name);
if ($data != 0) {
$this->load->view('/main/banquet_view', $data);
}
}
Model:
function talk_to_new_guest_table($guest_name) {
$query = $this->db->query(" SELECT guest_name, guest_gender, guest_nic_pp_dl
FROM new_guest
WHERE guest_name LIKE '$guest_name%'
LIMIT 1 ");
if($query->num_rows()>0) {
return $query->result();
}
else {
return 0;
}
}
View:
<div class="control-group">
<label for="guest_name" class="control-label"><i class="icon-user"></i> Name: </label>
<div class="controls">
<div class="input-append">
<input type="text" id="appendedInputButtons" class="span2" name="guest_name" value="<?php echo $guest_name; ?>">
<input class="btn" type="submit" name="searchGuest" value="Search">
</div>
<?php echo form_error('guest_name'); ?>
</div>

Categories