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 ;
}
Related
I am new to CodeIgniter
I have the following code in my Model:
public function saveVar() {
$variable_limit=$this->input->post('var');
$data = array(
'variable_limit'=>'$variable_limit'
);
$this->db->insert('mytable',$data);
}
this should fetch Data from html form and insert a row 'variable_limit' into the table 'mytable', the code doent work I see no change in the mysql database.
Assumed that the first code works, I want to display this data to the view, I wrote this Code in my Controller:
function postVar(){
$this->load->model('tool');
$this->tool->saveVar();
}
I am trying to transfer the data to the model calling 'tool' by calling the saveVar() which is implemented in my model, does this Code work?
Edit: this is the Code in my View:
<form id="myform" action="<?php echo base_url()."tools/file";?>" method="post" onsubmit="return validateData();">
<div> Variable : <input type="number" id="var" name="var" value="<?php echo isset($_POST['var']) ? $_POST['var'] : '' ?>" /></div>
Thanks, Elmoud
Do like this:-
Controller:-
public function postVar(){
$variable_limit=$this->input->post('var');
$data = array(
'variable_limit'=>$variable_limit
);
$this->tool->saveVar($data);
}
Model:-
public function saveVar($data) {
$this->load->model('tool');
$this->db->insert('mytable',$data);
}
Controller:
function postVar(){
$this->load->model('tool');
$this->tool->saveVar();
}
Model
public function saveVar() {
$variable_limit=$this->input->post('var');
$data = array(
'variable_limit'=>$variable_limit
);
$this->db->insert('mytable',$data);
}
It need not use quotes for variables.Just use $variable_limitas such.
Controller:
function postVar(){
$this->load->model('tool');
$this->tool->saveVar();
}
Model:
public function saveVar() {
$data = array(
'variable_limit'=>$this->input->post('var')
);
$this->db->insert('mytable',$data);
}
I'm new to CI and just trying to build a basic blog for practice. Everything works fine (pull all posts, individual posts, add new post, delete post) except for the update posts. The update form loads fin, but When I submit the form I get a blank page with no errors and nothing gets updated on the db. I've searched stack for solutions, but none of these seem to make a difference. Any help would be greatly appreciated.
EDIT: Now spits the following error:
Fatal error: Call to undefined method Post::where() in /Applications/MAMP/htdocs/CodeIgniter_2.2.0/application/models/post.php on line 26
Which is the first line inside the update_post model function:
function update_post($postID, $data){
$this->where('postID', $postID);
$this->db->update('posts', $data);
}
HTML form markup from the view edit_post.php:
Add new post
<?php if($success==1){ ?>
<p>Post successfully updated</p>
<? } ?>
<form action="<?=base_url()?>posts/editpost/<? echo $post['postID']?>" method="post">
<p>Title
<input name="title" type="text" value="<?=$post['title']?>" />
</p>
<p>Body
<textarea name="post"><?=$post['post']?></textarea>
</p>
<p><input type="submit" value="Edit Post" /></p>
</form>
Models:
class Post extends CI_Model{
function get_posts($num=20, $start=0){
//$sql="SELECT * FROM users WHERE active=1 ORDER BY date_added DESC LIMIT 0,20;";
$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->insert_id();
}
function update_post($postID, $data){
$this->where('postID', $postID);
$this->db->update('posts', $data);
}
function delete_post($postID){
$this->db->where('postID', $postID);
$this->db->delete('posts');
}
}
Controller:
class Posts extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('post');
}
function index(){
$this->load->model('post');
$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().'posts/');
}else{
$this->load->view('new_post');
}
}
function editpost($postID){
$data['success']=0;
if($_POST){
$data_post=array(
'title'=>$_POST['title'],
'post'=>$_POST['post'],
'active'=>1
);
$this->post->update_post($postID, $data);
$data['success']=1;
}
$data['post']=$this->post->get_post($postID);
$this->load->view('edit_post', $data);
}
function deletepost($postID){
$this->post->delete_post($postID);
redirect(base_url().'posts/');
}
}
You missed the db call before where. Here:
function update_post($postID, $data){
$this->where('postID', $postID);
$this->db->update('posts', $data);
}
Replace:
function update_post($postID, $data){
$this->db->where('postID', $postID);
$this->db->update('posts', $data);
}
you can try to debug it by using the below line in the model function
echo $this->db->last_query();
It will print the last query executed, and you can try to run it manually to check whether the query is fine or not, or try to debug it by putting logs.
OR add
error_reporting(E_ALL);
In the controller to display all the errors.
Hi there Iam using codeIgniter and I have managed to simply post a id number and phone number into the a table named "offers" both fields are INT, however when i try update a phone number corresponding to a specific id I see no changes in the database. I have listed my controller , model and view below
newOffer controller
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//insert data into db using offer_model model
// other option update submit
class newOffer extends CI_Controller {
function addOffer() {
//if the form is submitted
$this->load->view("check");
$this->load->model("offer_model");
if ($this->input->post('mysubmit')) {
$this->offer_model->entry_insert();
}
}
function updateOffer (){
$this->load->view("check2");
$this->load->model("offer_model");
if ($this->input->post('mysubmit')) {
$this->offer_model->upddata();
}
}
}
?>
offer_model
class offer_model extends CI_Model{
public function entry_insert(){
$data = array(
'idNum' => $this->input->post('idNum'),
'phneNum' => $this->input->post('phneNum'),
);
$this->db->insert('offers',$data);
}
public function upddata($data) {
$this->db->where('idNum', $idNum);
$this->db->update('data' ,$data);
//extract($data);
//$data['OfferName']
//$this->db->where('OfferName' , $data['OfferName']);
//$this->db->update($Offers, array('OfferName' => $OfferName));
return true;
}
}
?>
The view to update the values
<?form _open(base_url()."index.php/newOffer/updateOffer")?>
<div class="form">
// <?php echo form_open('newOffer/addOffer'); ?>
<legend>Please enter details for your new offer</legend>
<label for="ID Number">ID Number: <span class="required">*</span></label>
<input type="text" name="idNum" id="idNum" placeholder="Please enter ID Number/>
<label for="phone Number">Phone Number:</label>
<input type="text" name="phneNum" id="phneNum " placeholder="Please enter phone Number"/>
<fieldset class="submit_field">
<?php echo form_submit('mysubmit', 'Submit Form'); ?>
</fieldset>
</div><!-- end of form div -->
?>
You aren't passing any data to your model here
$this->offer_model->upddata();
You need to add something like
$this->offer_model->upddata($this->input->post());
Also in your Model code $idNum is undefined you will need to provide that too.
e.g:
public function upddata($data) {
$idNum = $data['idNum'];
unset($data['idNum']);
$this->db->where('idNum', $idNum);
$this->db->update('offers' ,$data);
return true;
}
//etc
Make sure you are feting from the same table in which you are inserting or updating data.
public function upload($id_akun, $data)
{
$table = "foto";
$this->db->where("id_akun", $data['id_akun']);
$count = $this->db->count_all_results($table);
if ($count < 1) {
$this->db->insert($table, $data);
} else {
$this->db->where('id_akun', $data['id_akun']);
$this->db->update($table, $data);
}
}
Good luck :)
Use construct for load your model in controller And always pass the post data to the model function then only you will find the form post data into model function.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function __construct()
{
parent::__construct();
$this->load->model("offer_model");
}
class newOffer extends CI_Controller {
function addOffer() {
//if the form is submitted
$this->load->view("check");
$this->load->model("offer_model");
if ($this->input->post('mysubmit')) {
$CI_Post = $$this->input->post();
$this->offer_model->entry_insert($CI_Post);
}
}
function updateOffer (){
$this->load->view("check2");
if ($this->input->post('mysubmit')) {
$CI_Post = $$this->input->post();
$this->offer_model->upddata($CI_Post);
}
}
}
?>
Here is model which getting form post data in array.
<?php
class offer_model extends CI_Model{
public function entry_insert($param=""){
$data = array(
'idNum' => $param['idNum'],
'phneNum' => $param['phneNum'],
);
$this->db->insert('offers',$data);
return $this->db->insert_id();
}
public function upddata($param="") {
$data = array(
'idNum' => $param['idNum'],
'phneNum' => $param['phneNum'],
);
$this->db->where('idNum', $idNum);
$this->db->update('data' ,$data);
return $this->db->affected_rows();
}
}
?>
in your model do something like
public function upddata() {
$data=array();
$data=$this->input->post(); //get all post value to data array
$idNum=$data['idNum'];
unset($data['idNum']); // unset unnecessary values
$this->db->where('idNum', $idNum)->update('offers' ,$data);
return true;
}
this is the procedure.If you have 100 input fields then its not possible to add every value to an array. Please let me know if you face any problem.
update
change
<?php echo form_open('newOffer/addOffer'); ?>
to
<?php echo form_open('newOffer/updateOffer'); ?>
in The view to update the values
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);
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.