How to update DB record using CodeIgniter? - php

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.

Related

form not submitting data to model in codeigniter

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

Yii dropdown with AJAX not working as expected

I have the following view named 'findreseller.php':
<?php
$countries = CHtml::listData(Country::model()->findAll(), 'id', 'name');
echo CHtml::dropdownlist('find_reseller', '', $countries,
array('ajax'=>array(
'type'=>'POST',
'url'=>Yii::app()->getController()->createAbsoluteUrl('/webcare/reseller/loadAjaxData'),
'update' =>'#data',
)
)
);
?>
<div id="data">
<?php $this->renderPartial('_ajaxContent', array('dataProvider'=>$dataProvider))?>
</div>
_ajaxContent just echoes the result, nothing special there...
The dropdown, as you can see is generated with CHtml because I dont't need a form. I just need an onChange event to do something...
As per the code that follows, in '/webcare/reseller/loadAjaxData' I have:
public function actionLoadAjaxData() {
$country = $_POST['find_reseller'];
//do something...
$dataProvider=new CArrayDataProvider($country_reseller);
$this->render('findreseller', array('dataProvider' => $dataProvider));
}
I can tell that I am missing something, but I am not sure what exactly.
Edit
Modified like this:
<?php
//CHtml::form();
$countries = CHtml::listData(Country::model()->findAll(), 'id', 'name');
echo CHtml::dropdownlist('find_reseller', '', $countries,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('/webcare/reseller/loadAjaxData'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city_id', //selector to update
'data'=>'js: $(this).val()',
//leave out the data key to pass all form values through
)
)
);
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city_id','', array());
//CHtml::endForm();
?>
<div id="data">
<?php $this->renderPartial('_ajaxContent', array('dataProvider'=>$dataProvider))?>
</div>
And now I get:
http://prntscr.com/42wwx6
And I have the following controller action:
public function actionLoadAjaxData() {
$country = $_POST['country_id'];
...
$dataProvider=new CArrayDataProvider($country_reseller);
$data = User::model()->findAll('country_id=:country_id AND reseller=:reseller',
array(':country_id'=>(int) $_POST['country_id'], ':reseller'=>1));
$data=CHtml::listData($data,'city','city');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
$this->render('action_name', array('dataProvider' => $dataProvider));
}
Edit 2
If I write a die in actionLoadAjaxData(), right at the beginning, the method is loaded fine, the action is ok and the server answers 200.

How to get the id from the url then insert it into the data base using codeigniter

Hopefully all this info helps out.
So what I am doing is i have a forum page that I have set up to were you can select a category, from that category you can insert a post into that category. What I need help with is getting the id of that category for the database so that post will show up when I echo it out. In other words linking ids to the pages upon insert.
ok so i know that its inserting the username message title ect but what its not doing is getting the 1 from the url and inserting that 1 into the database under category_id
Here is my url I left out the main http to shorten this up but the rest of it were the number 1 is what I am wanting to get and insert cause that its going to change depending on the category you choose. index.php/forum/create_post/1
This is what my category table has
ID title
1 community
This is what my post table has were all the main info comes from and were I am wanting to connect the category_id to the main category table.
id, title message date user id category_id flaged username
This is the first view that will insert the new post
View:
<div id="container">
<div class="module">
<?php echo form_open('forum/create_post'); ?>
<div>
<?php
echo form_label('Title', 'title');
echo form_input('title', '');
?>
</div>
<div>
<?php
echo form_label('Message', 'message');
echo form_input('message', '');
?>
</div>
<div>
<?php echo form_submit('create', 'create new post'); ?>
</div>
<?php echo form_close(); ?>
</div>
</div>
Controller: here is the section in the controller were I am passing all my input if no to
public function create_post() {
if( !$this->session->userdata('username') ) {
redirect('/'); // please login to continue
}
if( $this->input->post('create') ) {
$this->forum->createpost(array(
// $id= $this->uri->segment(3),
'title' => $this->input->post('title'),
'message' => $this->input->post('message'),
'user_id'=> $this->session->userdata('id'),
'username'=>$this->session->userdata('username'),
));
}
$this->load->view('templates/header');
$this->load->view('forum/create_post');
$this->load->view('templates/footer');
}
Here is the model that i'am inserting the data to
public function createpost($data){
$this->db->insert('post',$data);
}
As per your URL index.php/forum/create_post/1, You controller function should be as below to meet CI Standard.
public function create_post($category_id) {
So you can access $category_id directly. No need to get url segment.
$res = $this->forum->createpost(array(
$id= $category_id,
'title' => $this->input->post('title'),
'message' => $this->input->post('message'),
'user_id'=> $this->session->userdata('id'),
'username'=>$this->session->userdata('username'),
));
if($res)
{
// show thanks msg
}
else
{
// show error msg
}
In your model:
You can check that data is inserted
public function createpost($data)
{
$this->db->insert('post',$data);
if($this->db->affected_rows()>0)
return true;
else
return false;
}
You are not sending /1 to the page again. Your form must send that /1 from original url.
<?php echo form_open('forum/create_post'); ?>
create_post method wont receive a 3rd segment, because it doesn't exists. Store category id in a input hidden and access it by $this->input->post('category_id'):
Controller
public function create_post() {
if( !$this->session->userdata('username') ) {
redirect('/'); // please login to continue
}
if( $this->input->post('create') ) {
$this->forum->createpost(array(
'category_id' => $this->input->post('category_id'),
'title' => $this->input->post('title'),
'message' => $this->input->post('message'),
'user_id' => $this->session->userdata('id'),
'username'=>$this->session->userdata('username')
));
}
$data['category_id'] = $this->uri->segment(3);
$this->load->view('templates/header');
$this->load->view('forum/create_post', $data);
$this->load->view('templates/footer');
}
View
<div id="container">
<div class="module">
<?php echo form_open('forum/create_post'); ?>
<div>
<?php
echo form_label('Title', 'title');
echo form_input('title', '');
?>
</div>
<div>
<?php
echo form_label('Message', 'message');
echo form_input('message', '');
?>
</div>
<div>
<?php echo form_submit('create', 'create new post'); ?>
</div>
<input type="hidden" name="category_id" value="<?php echo $category_id; ?>">
<?php echo form_close(); ?>
</div>
</div>
Also, ask yourself if there is a need to storage user ID and username. Isn't username attached to an ID? Couldn't it be retrieved by just selecting userID from a post?
I found out what i needed to do make this all work i had to insert the uri segment into a hidden input forum to get it to insert into the right id box and now iam able to connect the right categorys

Having Issues Invoking Actions Of Controller On Button Click

I'm having a problem calling an action in a controller upon button click. So the controller is generated by Gii. All of its actions are the default ones generated by Gii, except for the actionCreate().
Here is the relevant code ::
class ProductsController extends Controller {
public function actionCreate() {
$model = new Products;
if (isset($_POST['params'])) {
// $model->attributes = $_POST['Products'];
//if ($model->save())
// $this->redirect(array('view', 'id' => $model->id));
echo 'Yes Working';
}
$this->render('create', array(
'model' => $model,
));
}
As its clear from the above code snippet this action is calling the view named create.php.
Here is create.php::
<div class="page">
<div class="container">
<div class="row">
<h2>Create Products</h2>
<?php echo $this->renderPartial('_form', array('model' => $model)); ?>
</div>
</div>
And here is the partially rendered form.
<?php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id' => 'products-form',
'action' => Yii::app()->createUrl('products/create'),
'enableAjaxValidation' => false,
));
?>
<div class="form-actions">
<?php
echo CHtml::submitButton('Create', array(
'submit' => 'EasyAesthetics/index.php/products/create',
'params' => '1'
));
?>
</div>
<?php $this->endWidget(); ?>
Now what I want is that upon clicking the button 'Create', it would call the actionCreate() method in the ProductsController. Right now the button is working and I'm being redirected to /demoProject/index.php/products/create, but the echo 'Yes Working' is not displaying.
Can anyone please show me how to achieve this. How can i invoke the create action again with just a button and just a 1 in the $_POST array.
I need to do this so that on clicking create the actionCreate() method will call the relevant components to create the necessary products.
if your "var_dump()"ed your "$_POST" , you would see sensorario answer.
and also you can set your froms send method to post if still not sending post.
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id' => 'products-form',
'action' => Yii::app()->createUrl('products/create'),
'enableAjaxValidation' => false,
'method' => 'post',
));
?>
or get your parameter like this(this sets by $_REQUEST):
$param = Yii::app()->request->getParam('Products' , null);
Take a look at the code generated by your form. When you have model called "Hello" with a field called "world", your form field will be
<input type="text" name="Hello[world]">
Try to change your action in this way:
class ProductsController extends Controller {
public function actionCreate() {
$model = new Products;
if (isset($_POST['Products'])) {
echo 'Yes Working';
}
$this->render('create', array(
'model' => $model,
));
}
}
Pay particular attention to these two lines:
$model = new Products;
if (isset($_POST['Products'])) {
Fields will takes the same name of model. In case of more models:
<input type="text" name="Model1[field1]">
<input type="text" name="Model1[field2]">
<input type="text" name="Model21[field2]">
<input type="text" name="Model2[field2]">
and so on ...

Codeigniter update form

I'm really new to CI and have been trying to create an update form class today, but I'm running into a dead end. I have my functions set up to create the form and publish the data to the database, I now need to be able to update this.
My edit form function is below:
public function edit_event()
{
$vars = array();
$data['form_url'] = $this->form_url;
if ($form_id = $this->EE->input->get('form_id'))
{
$data['form_id'] = $form_id;
}
return $this->EE->load->view('edit_event', $data, TRUE);
}
and the edit_event file loaded within the function is:
<?php
$this->EE=& get_instance();
$this->load->helper('form');
$attributes = array('class' => 'event_form', 'id' => 'my_event_form');
echo form_open($form_url.AMP.'method=update_form', $attributes);
$this->EE->load->library('table');
$this->EE->table->set_heading(
'Preference',
'Setting'
);
$query = $this->EE->db->query("SELECT * FROM exp_events WHERE id = '$form_id'");
foreach($query->result_array() as $row)
{
$this->EE->table->add_row(
form_label('Application Key', 'app_key'),
form_input('app_key',$row['app_key'])
);
$this->EE->table->add_row(
form_label('Access Token', 'access_token'),
form_input('access_token',$row['access_token'])
);
$this->EE->table->add_row(
form_label('User Key', 'user_key'),
form_input('user_key',$row['user_key'])
);
}
echo $this->EE->table->generate();
echo form_reset('reset', 'Clear Form');
echo form_submit('mysubmit', 'Submit Post!');
echo form_close();
?>
I then have my update form function:
public function update_form()
{
$form_id = $this->EE->input->get('form_id');
$data['form_id'] = $form_id;
$form_data = array(
'app_key' => $this->EE->input->post('app_key'),
'access_token' => $this->EE->input->post('access_token'),
'user_key' => $this->EE->input->post('user_key')
);
$this->EE->db->where('id', $form_id);
$this->EE->db->update('exp_events', $form_data);
$this->EE->functions->redirect($this->base_url);
}
When removing the $form_if option I can get the data to update, but it updates for every single item in the database. I obviously need this to only update the data with the form id of the form being edited.
As it stands, when I submit the update form, I get redirected to my $base_url which is correct, but no data gets updated, therefore I am clearly doing something wrong when defining the form id?
As I said I'm new to this, so if anyone notices any preferred methods feel free to let me know :).
Any pointers appreciated.
Thanks in advance.
Ben
You need to include a 'hidden' field in your form, with the form_id. At the moment your 'form_id' is not part of your input, so when you go and get the form_id it is failing.
change
echo $this->EE->table->generate();
echo form_reset('reset', 'Clear Form');
echo form_submit('mysubmit', 'Submit Post!');
to
echo $this->EE->table->generate();
echo form_hidden('form_id', $form_id);
echo form_reset('reset', 'Clear Form');
echo form_submit('mysubmit', 'Submit Post!');

Categories