insert and update in single form in CodeIgniter - php

Here I have controller news.php:
<?php
class News extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model('news_model');
$this->load->helper('url_helper');
}
public function index(){
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
public function view($slug = NULL)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = "News in Detail(s)";
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item 22';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
$data['updateid'] = '' ;
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
if($update == 1){
redirect('/news', 'location');
}
}
}
public function update($id){
$this->load->helper('form');
$this->load->library('form_validation');
$data['updateid'] = $id;
$data['title'] = "Update News in Detail(s)";
$data['update'] = $this->news_model->edit_load_data($id);
$this->load->view('news/create',$data);
if ($this->input->post('submit')) {
$update = $this->news_model->update_news($id);
if($update == 1){
redirect('/news', 'location');
}
}
}
}
?>
Here my model file news_model.php:
<?php
class News_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function get_news($slug= false){
if($slug == false){
$query= $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
//'text' => $this->input->post('text')
'text' => $this->input->post('select')
);
return $this->db->insert('news', $data);
}
public function edit_load_data($id){
$query = $this->db->get_where('news', array('id' => $id));
return $query->row_array();
}
public function update_news($id){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
//'text' => $this->input->post('text')
'text' => $this->input->post('select')
);
$this->db->where('id', $id);
return $this->db->update('news', $data);
}
}
?>
Here my form create.php file:
<?php echo validation_errors();
echo $updateid;
?>
<?php if($updateid == ''){ ?>
<?php echo form_open('news/create'); ?>
<?php } else { ?>
<?php echo form_open('news/update/'.$updateid); ?>
<?php } ?>
<label for="title">Title</label>
<input type="input" name="title" value="<?php echo $update['title']; ?>" /><br />
<label for="text">Text</label>
<textarea name="text" ><?php echo set_value('text'); ?></textarea><br />
<label for="text">Select</label>
<select name="select">
<option <?php if($update['text']=='text1'){ echo "selected";} ?> value="text1">text1</option>
<option <?php if( $update['text']=='text2'){ echo "selected";} ?> value="text2">text2</option>
</select>
<br />
<input type="submit" name="submit" value="Create news item" />
</form>
Here when I am going news/create in gives error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: update
Filename: news/create.php
Line Number: 15
Backtrace:
File: C:\xampp\htdocs\mylab\application\views\news\create.php Line: 15
Function: _error_handler
File: C:\xampp\htdocs\mylab\application\controllers\News.php Line: 54
Function: view
File: C:\xampp\htdocs\mylab\index.php Line: 315 Function: require_once
" />
What can I do for that? I want add and edit for same file create.php
is it possible there?

I don't know that this will produce the outcome you want but it will prevent the use of undefined variables.
<?php
echo validation_errors();
$updateid = isset($updateid) ? $updateid : '';
echo $updateid;
if($updateid == '')
{
echo form_open('news/create');
}
else
{
echo form_open('news/update/'.$updateid);
}
if(!isset($update))
{
$update['title'] = NULL;
$update['slug'] = NULL;
$update['text'] = NULL;
}
?>
<label for="title">Title</label>
<input type="input" name="title" value="<?php echo $update['title']; ?>" /><br />
<label for="text">Text</label>
<textarea name="text" ><?php echo set_value('text'); ?></textarea><br />
<label for="text">Select</label>
<select name="select">
<option <?php
if($update['text'] == 'text1')
{
echo "selected";
}
?> value="text1">text1</option>
<option <?php
if($update['text'] == 'text2')
{
echo "selected";
}
?> value="text2">text2</option>
</select>
<br />
<input type="submit" name="submit" value="Create news item" />
</form>
You should probably modify your model so that it returns a default array if/when the inputs are not present. I am not able to identify where you are sending $update to the view either.

I think you're not returning $update['title'], $update['text'], etc.. You are returning $title, $text...
Try changing $update['title'] to $title in create.php to see what
happens

Related

Too few arguments to function Admin::edit(),

I'm new in codeigniter and php,
and am trying to create crud (update)
how to solve this?
thanks in advance
Model :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Role_model extends CI_Model
{
public function DeleteRole($id)
{
$this->db->where('id', $id);
$this->db->delete('user_role');
}
public function GetId($id)
{
return $this->db->get_where('user_role', ['id' => $id])->row_array();
}
public function EditRole()
{
$data = [
"role" => $this->input->post('role' , true)
];
$this->db->where('id', $this->input->post('id'));
$this->db->update('user_role', $data);
}
}
controller :
public function __construct()
{
parent::__construct();
is_logged_in();
$this->load->model('Role_model');
}
public function edit($id)
{
$data['title'] = 'Role';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$data['user_role'] = $this->Role_model->GetId($id);
$this->form_validation->set_rules('role', 'Role', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('admin/edit', $data);
$this->load->view('templates/footer');
} else {
$this->Role_model->EditRole();
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Role Edited!</div>');
redirect('admin/role');
}
}
view :
<div class="card-body">
<?= $this->session->flashdata('message'); ?>
<form action="<?= base_url('admin/edit/');?>" method="post">
<input type="hidden" name="id" value="<?= $user_role['id']; ?>">
<div class="form-group text-gray-900">
<label for="role">Edit Role</label>
<input type="text" class="form-control" id="role" name="Role" value="<?= $user_role['role']; ?>">
<?= form_error('role', ' <small class="text-danger pl-3">', '</small>'); ?>
</div>
</div>
and it display like this
An uncaught Exception was encountered
Type: ArgumentCountError
Message: Too few arguments to function Admin::edit(), 0 passed in
C:\xampp\htdocs\KingflowWP2\system\core\CodeIgniter.php on line 532 and exactly 1 expected
Let me explain to you.
Edit function needs one parameter (i.e. id). In your form, you are submitting the form without id.
You just need to add the id at the end of the URL like below. Suppose id is 2 then you have to add 2.
base_url('admin/edit/2')
<form action="<?= base_url('admin/edit/2');?>" method="post">
You are only passing $id in
$this->usermodel->Role_model($get['id']);
You have to change your function if you want to post value in hidden input. Oner more thing you have to use default argument if you are not sure about the data is present or not. Always check step by step that data is present or not than do anything.
Write echo here so you get the value in hidden field
<input type="hidden" name="id" value="<?php echo $user_role['id']; ?>">
After that change in the function:
public function edit()
{
$id = $this->input->post('id');
$data['title'] = 'Role';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
if(!empty($id)):
$data['user_role'] = $this->Role_model->GetId($id);
else:
//some error message
endif;
$this->form_validation->set_rules('role', 'Role', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('admin/edit', $data);
$this->load->view('templates/footer');
} else {
$this->Role_model->EditRole();
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Role Edited!</div>');
redirect('admin/role');
}
}

codeigniter pass data from view to controller

I encountered problem with codeigniter. I want to update my profile page. I have problem when passing data from textbox in view to controller. In controller Profile.php, i have print_r $data that show no data get from view. Hope you guys can help me. Thank you.
View profile.php
if(isset($profile)){
?>
<?php echo validation_errors();?>
<?php echo form_open('profile/update_profile'); ?>
<div class="field half first"><input type="password" name="pass" placeholder="Password" value="<?php echo $profile['password']; ?>" /></div>
<div class="field half"><input type="password" name="con_pass" placeholder="Confirm Password" value="<?php echo $profile['con_password']; ?>" /></div>
<div class="field half"><input type="text" name="phone_no" placeholder="Phone Number" value="<?php echo $profile['phone_no']; ?>" /></div>
<li><?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?></li>
</ul>
<?php echo validation_errors();?>
<?php echo form_close(); ?>
<?php
}
?>
Controller Profile.php
public function update_profile(){
$email = $_SESSION['email'];
// $data['profile'] = $this->profile_model->getprofile($email);
$data = array(
'password' => $this->input->post('pass'),
'con_password' => $this->input->post('con_pass'),
'phone_no' => $this->input->post('phone_no')
);
print_r($data);
if($this->profile_model->updateprofile($email,$data))
{
$this->load->view('provider/profile', $data);
}
}
Model profile_model.php
public function updateprofile($email, $data){
$this->db->where('email', $email);
return $this->db->update('user', $data);
}
}
Try like below with form validation
https://www.codeigniter.com/user_guide/libraries/form_validation.html
https://www.codeigniter.com/user_guide/libraries/form_validation.html#rule-reference
EXAMPLE
public function update_profile() {
$this->load->library('form_validation');
// You can change what you want set for the rules your self this just example:
$this->form_validation->set_rules('pass', 'pass', 'trim|required');
$this->form_validation->set_rules('con_pass', 'con_pass', 'trim|required|matches[pass]');
$this->form_validation->set_rules('phone_no', 'phone_no', 'trim|required');
if ($this->form_validation->run() == TRUE) {
// Update model stuff
}
$email = $_SESSION['email']; // User id instead of email.
$profile_data = $this->users_model->getprofile($email);
if ($this->input->post('pass')) {
$data['pass'] = $this->input->post('pass');
} elseif (!empty($profile_data)) {
$data['pass'] = $profile_data['pass'];
} else {
$data['pass'] = '';
}
if ($this->input->post('con_pass')) {
$data['con_pass'] = $this->input->post('con_pass');
} elseif (!empty($profile_data)) {
$data['con_pass'] = $profile_data['con_pass'];
} else {
$data['con_pass'] = '';
}
if ($this->input->post('phone_no')) {
$data['phone_no'] = $this->input->post('phone_no');
} elseif (!empty($profile_data)) {
$data['phone_no'] = $profile_data['phone_no'];
} else {
$data['phone_no'] = '';
}
$this->load->view('provider/profile', $data);
}
Model function
public function getprofile($email) {
$this->db->where('email', $email);
$query = $this->db->get('users');
return $query->row_array();
}
View Example
<?php echo form_open('profile/update_profile'); ?>
<?php echo validation_errors();?>
<input type="password" name="pass" value="<?php echo set_value('pass', $pass);?>"/>
<input type="password" name="con_pass" value="<?php echo set_value('con_pass', $con_pass);?>"/>
<input type="text" name="phone_no" value="<?php echo set_value('phone_no', $phone_no);?>" />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?>
<?php echo form_close();?>

codeigniter and form submit

I am trying to get used to Codeigniter. I am sorry if that is a trivial or dumb question but I have been struggling to have the "News Section" of Codeigniter's tutorial work.
There is this form (from here)
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create'); ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
which, according to this controller:
<?php
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
$this->load->helper('url_helper');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'My News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
public function view($slug = NULL)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/', $data);
$this->load->view('templates/footer');
}
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');
}
}
}
should, I think, if the validation returns ok, go ahead and insert the data into the db. Now, my problem is that the pages run under:
http://localhost/codeigniter/index.php/news/
The submit button, however, returns me to:
http://localhost/codeigniter/index.php/news/localhost/codeigniter/index.php/news/create
The routes.php file contains the following code:
$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'news/view/$1';
$route['default_controller'] = 'news';
I don't know why this is happening. Thank you for any help.
Did you set your base_url config in application/config/config.php ?

Not able to insert into database using CodeIgniter

I am trying to insert data into database through Codeigniter, but I am not able to proceed. I have a database mydatabase with 5 tables training_assignment_id,assignment_name, assignment_description, recordings_required, and is_active. training_assignment_id is auto-increment.
Controller-1 training.php
<?php
class Training extends MY_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->helper(array('form'));
$this->load->view('training_admin');
}
/*
function input()
{
$this->load->model('training');
if($this->input->post('mysubmit')){
$this->training->training_assignment_insert();
}
}*/
}
?>
Controller-2 add_training.php
<?php
class Add_training extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('training');
}
/*function index($assignment, $description, $check, $radio)
{
$assignment=$this->input->post('assignment');
$description=$this->input->post('assignment2');
$check=$this->input->post('assignment3');
$radio=$this->input->post('is_active');
//query the database
if($assignment!=NULL || $description!=NULL || $check!=NULL || $radio!=NULL)
{
$this->training->training_assignment_insert($assignment, $description, $check, $radio);
echo 'inserted successfully';
}
else {
echo "Data has not been inserted";
}
}*/
function index()
{
$this->training->training_assignment_insert(); // this should forward them to the Model
}
}
?>
Model training.php
<?php
Class Training extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function training_assignment_insert($data ){
$data = array(
'assignment' => $this->input->post('assignment', TRUE),
'description' =>$this->input->post('assignment2', TRUE),
'check' => $this->input->post('assignment3', TRUE),
'radio' => $this->input->post('is_active', TRUE)
);
$this->db->insert('training_assignment', $data);
}
}
?>
View training_admin.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>resources/training/mystyle.css">
<title>Assignment</title>
</head>
<body>
<div id="container">
<h1>Add Assignment</h1>
<div id="body">
<?php echo form_open('traning/add_training'); ?>
<div id="label">
<input type="text" name="assignment" placeholder="Assignment Name" style="margin-left: 15px;"/>
<br/>
<textarea rows="4" cols="30" name="assignment2" placeholder="Assignment Description" style="margin-left: 15px;"></textarea>
<br/>
<label>Recording Require: </label>
<select name="assignment3">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
<br/>
<label for="active">Enable </label>
<input type="radio" name="is_active" id="enable" value="1"/>
<label for="female">Disable </label>
<input type="radio" name="is_active" id="disable" value="0"/>
<br/>
<input class="class1" type="submit" value="Assign"/>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>
</div>
</form>
</body>
</html>
Please anyone help me I am new for the CodeIgniter.
do this
controller
<?php
class Add_training extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('training');
}
function index()
{
$insert = array(
'assignment' => $this->input->post('assignment', TRUE),
'description' =>$this->input->post('assignment2', TRUE),
'check' => $this->input->post('assignment3', TRUE),
'radio' => $this->input->post('is_active', TRUE)
);
$this->training->training_assignment_insert($insert); // this should forward them to the Model
}
}
?>
model
<?php
Class Training extends CI_Model
{
function __construct()
{
parent::__construct();
// $this->load->database();
}
function training_assignment_insert($data ){
$query = $this->db->insert('training_assignment', $data);
if($query){
return true;
}
}
}
?>
you need to pass post values to model try
controller
function index()
{
$data = array(
'assignment' => $this->input->post('assignment', TRUE),
'description' =>$this->input->post('assignment2', TRUE),
'check' => $this->input->post('assignment3', TRUE),
'radio' => $this->input->post('is_active', TRUE)
);
$this->training->training_assignment_insert($data); // this should forward them to the Model
}
and model :-
function training_assignment_insert($data ){
$this->db->insert('training_assignment', $data);
}

Error 500 after submitting the form in codeigniter

Using these MVC, I get Error 500. Any ideas?
Controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Download extends CI_Controller {
function __construct()
{
parent::__construct();
parent::__construct();
$this->load->library('form_validation');
$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('upload_model');
//$this->output->enable_profiler(TRUE);
}
function index()
{
$this->form_validation->set_rules('enter_product_name',
'Enter Product Name',
'required|max_length[200]');
$this->form_validation->set_rules('test_type',
'Test Type',
'required|max_length[200]');
$this->form_validation->set_rules('test_unit',
'Test Unit',
'required|max_length[200]');
$this->form_validation->set_rules('project_code',
'Project Code',
'required|max_length[200]');
$this->form_validation->set_error_delimiters('<br /><span class="error">',
'</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$data->page = 'download_form_view';
$this->load->view('container', $data);
// $this->load->view('upload_form_view');
}
else // passed validation proceed to post success logic
{
// build array for the model
$file_name_info = $this->input->post('enter_product_name')
.'_'. $this->input->post('test_type')
.'_'. $this->input->post('test_unit')
.'_'. $this->input->post('project_code');
$filename_data = array(
'download_name' => $file_name_info
);
// run insert model to write data to db
if ($this->download_model->DownloadName($filename_data) == TRUE)
{
//redirect('download/download');
$this->download();
}
else
{
echo 'An error occurred while saving your filename to database. Please contact Admin with Issue No.[1]';
// Or whatever error handling is necessary
}
}
}
function download()
{
$this->load->helper('download');
$this->db->select('download_name');
$this->db->where("id", "0");
$this->db->limit(1);
$query = $this->db->get('downloadname');
$download_save_name = $query->row()->download_name;
$data = file_get_contents("./uploads/$download_save_name.xlsx");
force_download("$download_save_name.xlsx", $data);
}
}
?>
View
<?php // Change the css classes to suit your needs
$attributes = array('class' => '', 'id' => ''); echo
form_open('download', $attributes); ?>
<p>
<label for="enter_product_name">Enter Product Name <span class="required">*</span></label>
<?php echo form_error('enter_product_name'); ?>
<br /><input id="enter_product_name" type="text" name="enter_product_name" value="<?php echo
set_value('enter_product_name'); ?>" /> </p>
<p>
<label for="test_type">Test Type <span class="required">*</span></label>
<?php echo form_error('test_type'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'LongTerm' => 'Long Term Study',
'ShortTerm' => 'Short Term Study',
'Experimental' => 'Experimental Study',
); ?>
<br /><?php echo form_dropdown('test_type', $options, set_value('test_type'))?> </p>
<p>
<label for="test_unit">Test Unit <span class="required">*</span></label>
<?php echo form_error('test_unit'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'Hyd' => 'Hyd Unit',
'Viz1' => 'Viz Unit-1',
'Viz2' => 'Viz Unit-2',
); ?>
<br /><?php echo form_dropdown('test_unit', $options, set_value('test_unit'))?> </p>
<p>
<label for="project_code">Project Code <span class="required">*</span></label>
<?php echo form_error('project_code'); ?>
<br /><input id="project_code" type="text" name="project_code" value="<?php echo set_value('project_code'); ?>" /> </p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?> </p>
<?php echo form_close(); ?>
Model
<?php
class Download_model extends CI_Model {
function __construct() { parent::__construct(); }
function DownloadName($filename_data)
{
$this->db->update('downloadname', $filename_data, "id = 0");
if ($this->db->affected_rows() == '1') { return TRUE; }
return FALSE; } } ?>
I think the problem is:
you loaded
$this->load->model('upload_model');
and in your model code you have given
class Download_model extends CI_Model {
change this to
class Upload_model extends CI_Model {

Categories