form not submitting data to model in codeigniter - php

I am trying to let the user update recipe info. When i hit submit it goes back to the recipes page but the info was not changed. basically i have no idea why the database is not being updated, i get no errors to help me figure it out either.
any help would be greatly appreciated, thank you.
here is my controller:
public function update(){
$data = array(
'id' => $this->input->post('recipe_id'),
'title' => $this->input->post('recipe_name'),
'description' => $this->input->post('recipe_description'),
'stars' => $this->input->post('rating'),
'directions' => $this->input->post('recipe_directions'),
'link' => $this->input->post('recipe_link'),
'genre' => $this->input->post('recipe_genre'),
'posted' => date('Y-m-d')
);
$this->recipe_model->update_recipe($data);
$this->recipes();
}
here is my Model:
function update_recipe($data){
$id = $data['id'];
unset($data['id']);
$this->db->where('id', $id);
$this->db->update('recipes' ,$data);
return true;
}
Here is my view
<?php
$attributes = array('id' => 'update-recipe-form');
echo form_open('addRecipe/update', $attributes); ?>
<input type="text" name="recipe_id" class="hide" value="<?php echo $recipe_id; ?>" placeholder="<?php echo $recipe_id; ?>">
<fieldset class="name">
<legend>Name of recipe</legend>
<input type="text" name="recipe_name" class="recipe_name" placeholder="<?php echo $recipe_title; ?>" value="<?php echo $recipe_title; ?>" tabindex="1">
</fieldset>

You don't pass data directly to Models, you pass data to Controllers that use models to do something.
class addRecipe extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model( 'my_model' );
$this->load->helper( 'form' );
}
function index() // The default view
{
$data_to_pass = array(
/* All the variables to pass to the view.
* This is what the form "preloads" when loaded the first time
*/
'recipe_title' => 'somevalue',
'recipe_description' => 'somevalue',
// etc...
);
$this->load->view( 'view_name', $data_to_pass );
}
function update()
{
// Do something with the data, use model methods, print it, etc.
// $this->my_model->do_something();
$id = $this->input->post('recipe_id');
$data = array(
'title' => $this->input->post('recipe_name'), // Title or Name here?
'description' => $this->input->post('recipe_description'),
'stars' => $this->input->post('rating'),
'directions' => $this->input->post('recipe_directions'),
'link' => $this->input->post('recipe_link'),
'genre' => $this->input->post('recipe_genre'),
'posted' => date('Y-m-d')
);
$success = $this->recipe_model->update_recipe( $id, $data );
if ( $success )
$this->load->view( /* your success view */ );
else
{
// Something went wrong
echo 'MySQL error message: ' . $this->db->_error_message();
exit;
}
}
}
Your model:
class Recipe_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database(); // If it's not auto-loaded
}
function update_recipe( $id, $data )
{
$this->db->where( 'id', $id );
$this->db->update( 'recipes', $data );
return ( $this->db->affected_rows() > 0 ); // False if no recipes were modified
}
}
And your form:
<?=form_open('addRecipe/update', array( 'id' => 'update-recipe-form' ) ); ?>
<?php
// Will produce <input type="hidden" name="hidden_variable" value="hidden_value" />
echo form_hidden('hidden_variable', 'hidden_value');
?>
<fieldset class="name">
<legend>Name of recipe</legend>
<input type="text" name="recipe_name" placeholder="<?=$recipe_title; ?>" value="<?=$recipe_title; ?>" tabindex="1">
</fieldset>
<!-- Add all other required fields... -->
<?php
// Will produce <input type="submit" name="submit_button_name" value="Update recipe" />
echo form_submit( 'submit_button_name', 'Update recipe' );
?>
<?=form_close(); ?>
You can get more info about the form helper here: http://www.codeigniter.com/user_guide/helpers/form_helper.html

Related

How do I use CodeIgniter's `set_value()` function when using `form_validation.php`?

Problem:
I've got a form I'm trying to re-populate via the CodeIgniter docs, and I'm trying to use the set_value() function in my view file, but I receive an error: Message: Call to undefined function set_value().
I saw elsewhere on StackOverflow solutions to a similar problem when using the set_rules() function to define validations on a field-by-field basis.
However, I've got all of my validations together in config/form_validation.php, as sets of rules. Because all of my validations are defined within the rule set, it seems a little different than when defining field-by-field.
My rule set, controller, model and view methods are below.
Any idea why my re-population is not working?
Thanks for any insight anyone can offer, I'm new to CodeIgniter and I might be misunderstanding how things are working.
Validation Rules via config/form-validation.php:
$config = array(
'create' => array (
array(
'field' => 'name',
'label' => 'product name',
'rules' => 'trim|required|min_length[5]',
),
array(
'field' => 'description',
'label' => 'product description',
'rules' => 'trim|required|min_length[5]',
),
array(
'field' => 'price',
'label' => 'product price',
'rules' => 'trim|required|min_length[1]|less_than[100000]|decimal',
),
),
);
In my Controller:
public function create()
{
// XSS FILTER $POST OBJECT
$new_product = $this->input->post(null, true);
// SEND TO MODEL
$this->load->model("Product_model");
$product = $this->Product_model->add_product($new_product);
// IF VALIDATIONS RETURN FALSE, STORE ERRORS IN FLASH SESSION
if ($product[0] === FALSE)
{
$this->session->set_flashdata('errors', $product[1]);
redirect("/products/new");
}
// IF VALIDATION PASSES, SEND HOME
redirect("/");
}
In my Model:
public function add_product($product)
{
$this->load->library("form_validation");
if ($this->form_validation->run("create") === FALSE)
{
// STORE ERRORS & SHIP BACK TO CONTROLLER:
return array(FALSE, validation_errors());
}
else
{
// Success, Escape strings and insert to DB and return TRUE (or item)
}
}
In my form View:
(The page which displays returned errors above the form)
<form action="./create" method="POST">
<input type="text" name="name" id="name" value="<?php echo set_value('name'); ?>">
<textarea name="description" id="description" cols="30" rows="10" value="<?php echo set_value('description'); ?>"></textarea>
<input type="number" name="price" id="price" value="<?php echo set_value('price'); ?>">
<input type="submit" value="Create">
</form>
Hope this will help you :
add form_helper in your controller or in autoload.php
In controller :
public function __construct()
{
parent::__construct();
$this->load->helper('form');
}
Or in autoload.php :
$autoload['helper'] = array('form','url');
For more : https://www.codeigniter.com/userguide3/libraries/form_validation.html#re-populating-the-form

How to update DB record using CodeIgniter?

I'm trying to update a record of a database.
Here is the code:
On my index page.
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div class="main">
<?php echo $news_item['text'] ?>
</div>
<p>View article</p>
<p>Delete article</p>
<p>Update article</p>
On my update.php page.
<h2>Update a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ?>
<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="Update news item" />
</form>
On my news.php page.
public function update($slug)
{
$this->load->helper('url');
$this->news_model->update_news($slug);
redirect ('news', 'refresh');
}
On my news_model.php page.
public function update_news($slug)
{
$this->load->helper('url');
$data = array(
'title' => $title,
'slug' => $slug,
'text' => $this->input->post('text')
);
$this->db->where('title', $slug);
$this->db->update('news', $data);
}
My routing page.
$route['news/update/(:any)'] = 'news/update/$1';
$route['news/delete/(:any)'] = 'news/delete/$1';
$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
I'm trying to update the record the user clicks on.
However, instead of sending the slug to the update page, which has the form on to update the record, the code runs all the way through and updates the record to "0" values.
EDIT:
After a few comments, I can now see your problem. This is how I would fix it;
Your index file seems fine. It's your update function, within your controller where the problem lies. You're expecting to see the update form, but you're not actually loading the view;
Try replace the function, with this one;
public function update($slug)
{
if (!$this->input->post('submit'))
{
// The form was NOT posted
// So we load the view
$data['selected_article'] = $this->news_model->get_by_slug($slug);
$this->load->view('update', $data);
}
else
{
// The form was submitted
$data = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text'),
);
$this->news_model->update_news($slug, $data);
}
}
Shouldn't this:
$data = array(
'title' => $title,
'slug' => $slug,
'text' => $this->input->post('text')
);
be this:
$data = array(
'title' => $this->input->post('title'), //-->post variable
'slug' => $slug,
'text' => $this->input->post('text')
);
Also, are you sure that the $title variable is exactly the same as $slug?
If $title= 'My title', and $slug= 'my-title', they won't match and this won't run as expected:
$this->db->where('title', $slug);
I added a function in my form model file, there I just want to update some of the records that previously have been uploaded in a db:
public function update_records($id_aUsar){
$data = array(
'asunto' => $this->input->post('tema'),
'remite' => $this->input->post('emite'),
'mensaje' => $this->input->post('content'),
'dirigido' => $this->input->post('paraGrupo'),
'fechaEnvio'=> $this->input->post('fechaEnvio'),
'observaciones' => $this->input->post('notas')
);
$this->db->where('id_masivos', $id_aUsar);
$this->db->set('fecha', 'NOW()', FALSE);
$this->db->update('masivos_texto', $data);
}
where $id_aUsar is the primary key id of the row I want to update, I get the id from my session value, in order to keep the same session (my primary key id_masivos is type AUTOINCREMENT), the array entries are the only data to be updated after the user updates some of the fields (all of then including), but only those I show in the function are essential to the records update. Then in my controller I access my model added fuction like this:
$this->forma_model->update_records($id_tarea);
where $id_tarea is the current session id for that user in that session, that´s how I update records without losing the primary key id.

Codeigniter approach to save all posted values in bidimensional array

I have a multiform and I need to insert several values to 4 user,news,feed,lat (maybe 6) tables that are related by some ID this is because an event needs all this information.
my form:
<form method="post" action="<?php echo base_url();?>controller/save" name="event"/>
<label>User Name</label>
<!--#####FOR TABLE USER#####-->
<input type="text" name="name">
<input type="text" name="name">
<!--#####FOR TABLE NEWS#####-->
<input type="text" name="title">
<input type="submit" value="body"/>
<!--#######################
OTHER TABLE FIELDS ...
#######################
-->
<input type="submit" value="save"/>
</form>
Now I would like to pass a bidimensional array to event model and then depending on value insert to corresponding table
controller event.php
class Event extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->model('event_model');
}
public function save()
{
/** Is it possible to fill this bidimensional array with for loops???? **/
$arr_data = array(
array("person", $this->input->post("name") , $this->input->post("address")),
array("news" , $this->input->post("title") , $this->input->post("body" )),
array("feed" , $this->input->post("id_feed") , $this->input->post("main" )),
array("lat" , $this->input->post("lat1" , $this->input->post("lat" ))
);
$this->event_model->insert_tables($arr_data);
}
}
Now How to receive the array in model and do the insert how to declare event_model?
class Event_model extends CI_Model {
function Event_model ()
{
parent::__construct();
}
function insert_tables($arr_data) {
if( "person" )
$this->db->insert(person_tb ,
}
}
Is it necessary to use implode or something, Is there a better way to do this multiple inserting?
I would do something like this...
$person = array('name' => $this->input->post("name"), 'address' => $this->input->post("address"));
$news = array('title' => $this->input->post("title"), 'body' => $this->input->post("body"));
$feed = array('id' => $this->input->post("id_feed"), 'main' => $this->input->post("main"));
$lat = array('lat1' => $this->input->post("lat1"), 'lat' => $this->input->post("lat"));
if($this->person_model->insert($person)) {
$person_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
if($this->news_model->insert($news)) {
$news_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
if ($this->feed_model->insert($feed)) {
$feed_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
if($this->lat_model->insert($lat)) {
$lat_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
Sounds really complicated...why not have a model for each entity and pass the right fields to the right model? Or create a library that inserts/updates each of your models?

Post Data Multiple Rows in a Form in Codeigniter

I want to select some data in the CodeIgnigher PHP application from the database and want to make some change and insert to another table. I would like to insert as as many as selected records into the IN table. Currently I am getting only one row inserted into the out table.
Can you please point, what is being done wrong here.
My tables are. Out_Table (id, name..) and In_Table (id, name, quantity..).
My Model Code is:
<?php
class ShoppingListM extends CI_Model {
public function getData() {
$query = $this->db->get('products');
return $query->result();
}
function SaveForm($form_data) {
$this->db->insert('SLists', $form_data);
if ($this->db->affected_rows() == '1') {
return TRUE;
}
return FALSE;
}
}
?>
View Code:
<div class="divTable">
<fieldset>
<!-- these will be affected by check all -->
<div class="divRow">Product Name | Quantity | Packages</div>
<div class="divRow"><input type="checkbox" size="100" class="checkall"> Check all</div>
<br>
<?php foreach ($records as $rec) {
?>
<div class="divRow"><input type="checkbox">
<input size="5" type="hidden" value="<? echo $rec->id; ?>" name="id"></input>
<input size="20" type="text" value="<? echo $rec->name; ?>" name="name"></input>
<input size="5" type="text" value="" name="quantity"></input>
<select name="package">
<option name="case">Case</option>
<option name="box">Box</option>
<option name="box">Single Bottle</option>
</select>
</div>
<br>
<?
}
?>
</fieldset>
</div>
<div><input type="submit" name="submit"/></div>
</form>
Controller Code:
class ShoppingListController extends CI_Controller {
public function index() {
//$data['val'] = array("test1", "test2", "test3");
// $this->load->model('HomeModel');
//$data['records'] = $this->HomeModel->getData();
$this->load->model('ShoppingListM');
$data['records'] = $this->ShoppingListM->getData();
$this->form_validation->set_rules('name', 'Name', 'required|max_length[255]');
$this->form_validation->set_rules('qty', 'qty', '');
$this->form_validation->set_rules('package', 'Package', 'required|max_length[128]');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('ShoppingListV', $data);
}
else // passed validation proceed to post success logic
{
// build array for the model
$form_data = array(
'name' => set_value('name'),
'quantity' => set_value('quantity'),
'package' => set_value('package')
);
// run insert model to write data to db
// run insert model to write data to db
if ($this->ShoppingListM->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('ShoppingListController/success'); // or whatever logic needs to occur
}
else
{
echo 'An error occurred saving your information. Please try again later';
// Or whatever error handling is necessary
}
}
well i cannt see where is in_table/out_table in the code u provided yet.
to insert many rows what u want insert_batch
example from doc
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
or u can loop all ur rows from in_table and insert them one by one if its a maintaince job that u dont care about multiple queries
$data= $this->db->get('Out_table');
try
{
if ( $data->num_rows == 0)
throw new Exception('table empty');
foreach( $data->result() as $row)
{
//modifiy the row as u want
$modified=$row;
$q=$this->db->insert('in_table',$modified);
if( ! $q )
throw new Exception('failed to insert row id:'.$row->id);
}
echo $data->num_rows.'rows inserted';
}
catch (Exception $e)
{
echo $e->getMessage();
// Stop method execution with return, or use exit
return;
}

why is my update query creating new row?

I'm using codeigniter and trying to do an UPDATE query, but it keeps creating a new row like an INSERT query. I'm baffled and searching the web didn't yield much for me. (I'm a bit of a n00b). Any help would be greatly appreciated.
Here is the form:
<form action="<?=base_url();?>blog/new_post" method="post" name="write_new">
<input type="hidden" name="user" value="<?=$user?>">
<label>Title:</label><br>
<input type="text" name="title" value="<?php if(isset($query->title)) { echo $query->title; }?>" size="50"><br>
<label>Date:</label><br>
<input type="text" name="date" size="46" value="<?php if(isset($query->date)) { echo $query->date; }?>" />
<script language="JavaScript">
new tcal ({
// javascript calender thingy
// form name
'formname': 'write_new',
// input name
'controlname': 'date'
});
</script> <br><br>
<label>Article:</label><br>
<textarea name="content" style="width:100%;height:300px;"><?php if(isset($query->article)) { echo $query->article; }?></textarea><br>
<select name="category">
<option value="news">Dreamsy News</option>
<option value="web">From the Interwebs</option>
</select>
<input type="submit"/>
</form>
<div class="clearboth"></div>
Here's the model:
function edit_post($title, $date, $author, $article, $category, $id)
{
$this->load->helper('form'); //loads the CI form helper
$this->load->library('form_validation'); //loads the form validation class
$this->form_validation->set_rules('title', 'title', 'required|min_length[3]|max_length[40]|xss_clean');
$this->form_validation->set_rules('date', 'date', 'required|min_length[5]|max_length[15]|xss_clean');
$this->form_validation->set_rules('category', 'category', 'required|xss_clean');
$this->form_validation->set_rules('content', 'article', 'required|xss_clean');
$this->form_validation->set_rules('user', 'you are not logged in', 'required');
if ($this->form_validation->run() == FALSE) //If the form does not validate
{
$this->load->vars(array('title' => 'Error'));
$this->template->write_view('content', 'error/new_post_fail');
$this->template->render();
}
else
{
$article = htmlentities($article, ENT_QUOTES);
/*$data = array(
'title' => $title,
'date' => $date,
'author' => $author,
'article' => $article,
'category' => $category
);*/
//$this->db->where('id', $id);
//$this->db->update('blog', $data);
$query = 'UPDATE blog SET title = '.$title.' date = '.$date.', author = '.$author.', article = '.$article.', category = '.$category;
$this->db->query($query);
redirect(base_url().'blog');
}
And here's the controller:
public function write()
{
$id = $this->uri->segment(3);
$query = 'SELECT * FROM blog WHERE id = '.$id;
$query = $this->db->query($query);
$query = $query->row();
$title = $query->title;
$user = $this->session->userdata('user_id');
if(isset($id)){ $title = 'Edit: '.$title; } else { $title = 'Write new post'; }
$vars['title'] = $title;
$vars['page'] = 'blog';
$vars['user'] = $user;
$vars['id'] = $id;
$vars['query'] = $query;
$this->load->helper('form'); //loads the CI form helper
$this->load->library('form_validation'); //loads the form validation class
$this->load->vars($vars);
$this->template->write_view('content', 'blog/write');
$this->template->render();
}
<form action="<?=base_url();?>blog/new_post" method="post" name="write_new">
You have to modify the action attribute to call the edit method of your blog controller. Otherwise the new_post method is called, which as far as I can see just inserts the POST data.
Did you set up some route, because i didnt see related function in your above controller which referencing by action tag/attr from your form. It hard to guest where the error came from, if you doesn't include that function.
Some highlight from me, i notice you put form validation, template stuff and even redirection function in models instead put that in your controller.
I think there is no WHERE condition in your UPDATE Query this can be one of the problem of your issue..
be sure only that part of the code is being executed for your problem..

Categories