value of FORM INPUT Help!!
//this is just a refrence of $nm and $fid from test_model//
$data['fid']['value'] = 0;
$data['nm'] = array('name'=>'fname',
'id'=>'id');
say i have one form_view with
<?=form_label('Insert Your Name :')?>
<?=form_input($nm)?>
and a function to get single row
function get($id){
$query = $this->db->getwhere('test',array('id'=>$id));
return $query->row_array();
}
then in controller.. index($id = 0)
and somewhere in index
if((int)$id > 0)
{
$q = $this->test_model->get($id);
$data['fid']['value'] = $q['id'];
$data['nm']['value'] = $q['name'];
}
and mysql table has something like 1. victor, 2. visible etc. as a name value
but here its not taking the value of name and id from form_input and not showing it again in form_view in same input box as victor etc so to update and post it back to database...
anyone please help!!
and please be easy as I am new to CI!!
Based on your comment to my first answer, here is a sample of a Controller, Model and View to update a user entry pulled from a table in a database.
Controller
class Users extends Controller
{
function Users()
{
parent::Controller();
}
function browse()
{
}
function edit($id)
{
// Fetch user by id
$user = $this->user_model->get_user($id);
// Form validation
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run())
{
// Update user
$user['name'] = $this->input->post('name', true);
$this->user_model->update_user($user);
// Redirect to some other page
redirect('users/browse');
}
else
{
// Load edit view
$this->load->view('users/edit', array('user' => $user));
}
}
}
Model
class User_model extends Model
{
function User_model()
{
parent::Model();
}
function get_user($user_id)
{
$sql = 'select * from users where user_id=?';
$query = $this->db->query($sql, array($user_id));
return $query->row();
}
function update_user($user)
{
$this->db->where(array('user_id' => $user['user_id']));
$this->db->update('users', $user);
}
}
View
<?php echo form_open('users/edit/' . $user['user_id']); ?>
<div>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo set_value('name', $user['name']); ?>" />
</div>
<div>
<input type="submit" value="Update" />
</div>
<?php echo form_close(); ?>
It's hard to see the problem from your snippets of code, please try and give a little more information as to the structure of your app and where these code samples are placed.
Presume in the last code listing ('somewhere in index') you are getting $id from the form, but you define the ID of the form input box as 'id' array('name'=>'fname','id'=>'id') rather than an integer value so maybe this is where the problem lies.
Where does the $data array get passed to in the third code listing?
From your question I think you want to display a form to edit a person record in the database.
Controller code
// Normally data object is retrieved from the database
// This is just to simplify the code
$person = array('id' => 1, 'name' => 'stephenc');
// Pass to the view
$this->load->view('my_view_name', array('person' => $person));
View code
<?php echo form_label('Your name: ', 'name'); ?>
<?php echo form_input(array('name' => 'name', 'value' => $person['name'])); ?>
Don't forget to echo what is returned from form_label and form_input. This could be where you are going wrong.
Related
I'd like to know how to prevent an insert into a database when the data is already existing inside it. And how to make an onclick window with a message that alerts the user that the data they're inserting is already inside the database.
How I get inputs from my view goes a little bit like this:
<form method="post" action="<?php echo base_url();?>index.php/Controller/insertdata">
<h3>Select Course Code:</h3>
<select id="employeeid" name="empid">
<option value="" selected="selected">---Select Course Code---</option>
<?php foreach ($e_id as $row4): ?>
<option label="<?php echo $row4['EmpID']; ?>" value="<?php echo $row4['EmpID']; ?>" <?php echo set_select('course', $row4['EmpID'], False); ?>> <?php echo $row4['EmpID'] ; ?> </option>
<?php endforeach; ?>
</select>
<input type="Submit" value="Submit" id="submite_id">
It takes data from the database into the select tag. My database has Employee ID, Employee name, Dept. code, and assignment.
Here's my Controller:
public function insertdata() {
$this->model->setdata();
$data['results'] = $this->model->emp_all();
$this->load->view('edit_view', $data);
}
It inserts the data into the database and redirects the user to a view.
And finally here's how I insert it into the database in my Model:
public function setData(){
$f1 = $_POST['empid'];
$f2 = $_POST['empname'];
$f3 = $_POST['deptcode'];
$f4 = $_POST['assignment'];
$this->db->query("INSERT INTO employeeDB VALUES('$f1', '$f2', '$f3', '$f4')");
}
The catch is that the users should not be able to assign an employee id, and name to a duplicate assignment on the same department.
Any reply, comment, and insight will be appreciated. Thanks in advance!
You can use INSERT IGNORE INTO query. It won't insert record in table if data is already exists.
Please have look here.
Hope this will help.
You can use Codeingiter form_validation library.
$this->load->library('form_validation');
$this->form_validation->set_rules('empid', 'Employee ID', 'required|trim|employeeDB.empid');
Where the last Parameter employeeDB.empid is used as table_name.column_name. So your Controller will be as below.
public function insertdata() {
$this->load->library('form_validation');
$this->form_validation->set_rules('empid', 'Employee ID', 'required|trim|employeeDB.empid');
if ($this->form_validation->run() == FALSE) {
// Form Validation Failed.
$this->load->view('myform');
} else {
// Form Validation Passed.
$this->model->setData();
$data['results'] = $this->model->emp_all();
$this->load->view('edit_view', $data);
}
}
in sql server use can use NOTEXIST for protect to duplicate insertion
here is my site_model code
get all data from database and insert data into database using Html form
please help i don't know where i do mistake
class Site_model extends CI_Model
{
public function __construct()
{
}
// get all data from database
public function get_records()
{
$query = $this->db->get('user_data');
return $query->result();
}
// add records into database by form
public function add_record($formData)
{
$this->db->insert('user_data', $formData);
}
}
than i load model into controller and get values in an array. and after create an array to send form values into database
class Site extends CI_Controller
{
var $data = array();
public function __construct()
{
parent::__construct();
$this->load->model('Site_model');
}
public function index()
{
//get data into array from model
$data = $this->data;
$data['user_info'] = $this->Site_model->get_records();
// get data from html form and send to database
$formData = array(
'title' => $this->input->post('post_title'),
'description' => $this->input->post('post_descrip')
);
// send record to model
$this->Site_model->add_record($formData);
$this->load->view('crud_viw', $data);
}
}
my view code look like this
<!DOCTYPE html>
<html>
<head>
<title>Crud</title>
</head>
<body>
// Html form to send values to database
<form method="post">
<input type="text" placeholder="Title" name="post_title"></input>
<input type="text" placeholder="Description" name="post_descrip"> </input>
<button type="submit">Submit</button>
</from>
</body>
</html>
Change your index method as below. You only have to enter data when post event occur
public function index()
{
//get data into array from model
$data = $this->data;
$data['user_info'] = $this->Site_model->get_records();
if($this->input->post()){ //<--- add this condition
// get data from html form and send to database
$formData = array(
'title' => $this->input->post('post_title'),
'description' => $this->input->post('post_descrip')
);
// send record to model
$this->Site_model->add_record($formData);
}
$this->load->view('crud_viw', $data);
}
in your database your column "title" should be not null..so mark "title" as not null in database..
Hope it helps..
The simple way to prevent getting the a database error occurred column 'title' cannot be null is use ternary operator(?:).If you have not posted value it will inserts empty string.
$formData = array(
'title' => isset($this->input->post('post_title'))?$this->input->post('post_title'):" ",
'description' => isset($this->input->post('post_descrip'))?$this->input->post('post_descrip'):" "
);
Hope it works.
I have a url of a page as
http://localhost/projectname/admin/client/1
In the above url i have a form in which i need to fill details and save it in database. The form on this page is:
<?php
$data = array(
'type'=>'text',
'name'=>'job_title',
'value'=>'Job Title',
'class'=>'form-control');
?>
<?php echo form_input($data); ?>
<?php
$data = array(
'type'=>'submit',
'class'=>'btn',
'name'=>'submit',
'content'=>'Submit!'
);
echo form_button($data);
?>
<?php
echo form_close();
?>
On the submission of the page i wish to save it in a table but along with it i also wish to carry the id/value which is in url (in this case it is 1), and would like to carry it forward till model so that i can perform actions in database based on this id/value. Can anyone please tell how it can be done
Present code for controller
public function form()
{
$this->form_validation->set_rules('job_title','Full Name','trim|required|min_length[3]');
if($this->form_validation->run() == FALSE)
{
$regdata = array
(
'regerrors' => validation_errors()
);
$this->session->set_flashdata($regdata);
redirect('admin/clients');
}
else
{
if($this->user_model->job())
{
redirect ('admin/client');
}
}
}
Present code for model // In the users table i wish to add job title to that row where the id matches the value in url i.e 1
public function job()
{
$data = array(
'job_title' => $this->input->post('job_title')
);
$insert_data = $this->db->insert('users', $data);
return $insert_data;
}
Try some thing like this:
$clientId = $this->uri->segment('3'); // will return the third parameter of url
Now put this $clientId in form in a hidden input. Now you can get the $clientId on controller function when form submits. Pass it to model or use accordingly.
I am trying to insert a row to the db using codeigniter.
Model-post.php
class Post extends CI_Model{
function get_posts($num=20, $start=0){
$this->db->select()->from('posts')->where('active',1)->order_by('date_added','desc')->limit($num,$start);
$query=$this->db->get();
return $query->result_array();
}
function get_post($postid){
$this->db->select()->from('posts')->where(array('active' => 1, 'postID'=>$postid))->order_by('date_added','desc');
$query=$this->db->get();
return $query->first_row('array');
}
function insert_post($data){
$this->db->insert('posts',$data);
return $this->db->return_id();
}
Controller-posts.php
class Posts extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('post');
}
function index(){
$data['posts'] = $this->post->get_posts();
$this->load->view('post_index', $data);
}
function post($postid){
$data['post']=$this->post->get_post($postid);
$this->load->view('post',$data);
}
function new_post(){
if($_POST){
$data =array(
'title'=>$_POST['title'],
'post'=>$_POST['post'],
'active'=>1
);
$this->post->insert_post($data);
redirect(base_url());
}
else{
$this->load->view('new_post');
}
}
View-new_post.php
<form action="<?php base_url(); ?>posts/new_post" method="action">
<p>Title: <input type="text" name="title"></p>
<p>Description: <input type="textarea" name="post"></p>
<input type="submit" value="Add post">
</form>
Index view-post_index.php
foreach ($posts as $post) { ?>
<div id-="container">
<div><h3><?php echo $post['title']; ?> </h3>
<?php echo $post['post']; ?>
</div>
</div>
<?php
}
The index page shows all the posts from db. On clicking the title it takes to post.php view to show the respective data. This part is fine.
While trying to add a new post in new_post.php it is not reflecting in the db nor showing any error. Also I used redirect_url to redirect to the index page after inserting. So it shows the same available posts. On clicking the title it keeps on adding posts/post to the url repeatedly. Clicking the title once after redirecting the url shows
http://localhost/Codeigniter/posts/posts/post/1
Again on clicking the title it adds
http://localhost/Codeigniter/posts/posts/post/post/1
Can anyone help me? Thanks!
There are numerous issues across the entire application. These are what I found:
Views
Two problems in your new_post view.
You are not echoing out your base_url . You need to replace your form's action attribute.
the method attribute should either have post or get. In this case it should be post
Change it like this:
From this:
<form action="<?php base_url(); ?>posts/new_post" method="action">
To this:
<form action="<?= base_url(); ?>posts/new_post" method="post">
alternatively you can do this:
<form action="<?php echo base_url(); ?>posts/new_post" method="post">
Controller
In your posts controller, your new_post() function should be like this:
function new_post() {
if ($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'post' => $this->input->post('post'),
'active' => 1
);
$id = $this->post->insert_post($data);// this is the id return by your model.. dont know what you wann do with it
// maybe some conditionals checking if the $id is valid
redirect(base_url());
} else {
$this->load->view('new_post');
}
}
Model
function insert_post() should not have $this->db->return_id();, instead it should be $this->db->insert_id();
in your model
function insert_post($newpost){
$this->db->insert('posts',$newpost);
// check if the record was added
if ( $this->db->affected_rows() == '1' ) {
// return new id
return $this->db->insert_id();}
else {return FALSE;}
}
any user input must be validated. if you are using Codeigniter then use its form validation and use its input library like:
$this->input->post('title')
an example for blog posts are in the tutorial https://ellislab.com/codeIgniter/user-guide/tutorial/create_news_items.html
otherwise in your controller -- check if the new post id did not come back from the model -- if it did not come back then just go to an error method within the same controller so you don't lose the php error messages.
if ( ! $postid = $this->post->insert_post($newpost); ){
// passing the insert array so it can be examined for errors
$this->showInsertError($newpost) ; }
else {
// success now do something else ;
}
I am trying to update a table where id of the row is entered and title is selected through a dropdown list, but I have two problems. Firstly Im not sure how to pass the data to the model, and the second problem is actually updating the table using active record.
controller class
function edit_profile($id)
{
$data = array(
'table_name' => 'user',
'id' => $id ,
'fullname' => $this->input->post('fullname')
);
if($this->user_model->upddata($data))
{
$data['msg']= 'Update Done';
$this->load->view('header_view',$data);
$this->load->view("edit_profile_view.php", $data);
$this->load->view('sidbar_user_view',$data);
$this->load->view('footer_view',$data);
}
else
{
$data['msg']= 'Update Not Done';
$this->load->view('header_view',$data);
$this->load->view("edit_profile_view.php", $data);
$this->load->view('sidbar_user_view',$data);
$this->load->view('footer_view',$data);
}
}
model class
function upddata($data) {
extract($data);
$this->db->where('id', $id);
$this->db->update($table_name, array('fullname' => $fullname));
return true;
}
view
<?php echo form_open("profile/edit_profile/$d->id"); ?>
<div class="tuple">
<h1>full name : </h1>
<input type="text" name="fullname" class="t-name" readonly value="<?=fullname; ?>" >
<div class="clear"></div>
</div>
<input type="submit" name="mysubmit" value="Save" id="mysubmit">
<?php echo form_close(); ?>
and when open url
/site/profile/edit_profile/1
i get this message
Fatal error: Call to a member function upddata() on a non-object
Try to load your model in controller like
function edit_profile($id) {
$this->load->model('user_model');
//Do other things
}
And it is optional like
function uppdata($data) {
$this->db->where('id', $data['id']);
$this->db->update($data['table_name'], array('fullname' => $data['fullname']));
return true;
}
From $data also you can directly get the relavent values.ANd you need to pass $data to the view file not the $data1 because it is un-defined and
Replace
$this->load->view("edit_profile_view.php", $data);
to
$this->load->view("edit_profile_view", $data);