Codeigniter update query not working with form - php

Hey guys I'm having trouble running an update query through a form in codeigniter. There is no error returned, but the query does not update in the database. It should be noted there's another form on the same page running an insert query that works fine.
View:
<?php
$modify = array(
'id' => 'modify-form',
'class' => ''
);
echo form_open('main/modify_idea', $modify);
$ta_modify = array(
'id' => $row->id,
'name' => 'ta_modify',
'label' => 'ta_modify',
'placeholder' => $row->idea,
'method' => 'Post'
);
echo form_textarea($ta_modify);
echo form_hidden('facebook_id', $session['id']);
echo "<div id='button'>";
echo form_submit('submit', 'Post');
echo "</div>";
echo form_close();
?>
Controller:
public function modify_idea() {
$this->load->model('idea');
$this->idea->modify_idea();
redirect('main/members');
}
Model:
public function modify_idea() {
$data = array(
'id' => $this->input->post('id'),
'idea' => $this->input->post('ta_modify'),
'facebook_id' => $this->input->post('facebook_id')
);
$query = $this->db->query("UPDATE idea SET `idea` = ? WHERE `id` =?", array($data['idea'], $data['id']));
return $query;
}
I've utilized the following resources but still no luck:
CodeIgniter MySQL query not working
CodeIgniter MySQL Query not returning any data, even though there definitely is data to be returned!
http://www.tutorialspoint.com/mysql/mysql-update-query.htm
https://www.codeigniter.com/userguide3/database/query_builder.html#deleting-data
As always, thanks for the help!

Pass your post data from controller to model
Change your controller code:
public function modify_idea() {
$this->load->model('idea');
$data = array(
'id' => $this->input->post('id'),
'idea' => $this->input->post('ta_modify'),
'facebook_id' => $this->input->post('facebook_id')
);
$this->idea->modify_idea($data);
redirect('main/members');
}
in model do this
public function modify_idea($data) {
$query = $this->db->query("UPDATE idea SET `idea` = ? WHERE `id` =?",
array($data['idea'], $data['id']));
return $query;
}

Please pass your post values to model from controller. Then it will work.

Related

last inserted id in Php codeIgniter

In my model I have return below function for get record id
function getLastInserted()
{
$query = $this->db->select("MAX(`UserID`)+1 as userid")->get("registeration");
return $query->result();
}
Now I want to pass that ID to mycontroller for record insertion
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
Now I want to access model function in controller and pass record id in data function How I do ??
set return in model and in controller write
$insert_id=$this->db->insert_id();
In Controller load your model first using
$this->load->model('model_name');
Then call to model's getLastInserted() function.
$ID = $this->model_name->getLastInserted();//you will get id here
In model return $query->row()->userid; insead return of $query->result().
Then modify the controller:
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $this->model_name->getLastInserted(),
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
hi i worked out the solution on last inserted id dear here the code:
controller:
function sample() {
$sid=$this->adminmodel->getLastInserted();
$this->adminmodel->newregistration( $sid);
}
model:
function getLastInserted()
{
$query = $query = $this->db->select('id')->order_by('id','desc')->limit(1)->get('employee_outs')->row('id');
return $query;
}
model:
public function newregistration($sid)
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $sid,
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}

Creating REST API with CakePHP

I have to create a REST API for mobile backend using CakePHP. After following the instructions here I have been able to setup the requirements for creating a REST API. The problem is that I am getting a null in my output when I use the _serialize variable. Here is my code:
class InvitationController extends AppController {
public $components = array('RequestHandler');
public function index() {
}
public function add() {
if ($this->request->is('post')) {
$this->loadModel('Organizer');
$numPeople = $this->request->data['numpeople'];
$share = $this->request->data['myshare'];
$organizer = $this->request->data['organizer'];
$organizerMobile = $this->request->data['organizermobile'];
$this->set('organizerMobile', $organizerMobile);
$deadline = $this->request->data['deadline'];
$links = array();
date_default_timezone_set("Asia/Calcutta");
$now = date('Y-m-d');
$lastOrganizer = $this->Organizer->find('first', array(
'order' => array('Organizer.id' => 'desc')
));
$checkOrganizer = $this->getOrganizerDetails($lastOrganizer);
$pass = //something;
// save data in organizers table
$this->organizer->create();
$this->organizer->save(
array(
'name' => $organizer,
'mobile' => $organizerMobile,
'p_id' => 1,
'share' => $share,
'deadline' => $deadline,
'password' => $pass,
'group_cardinality' => $numPeople,
'created_on' => $now,
)
);
$message = 1;
$this->set(array(
'message' => $message,
'_serialize' => array($message)
));
}
}
}
When I make a request to POST /invitation.json I get null in the ouput with status 200. On the other hand if I simply do echo json_encode($message) in the Controller or in the View I get the correct output. I think I am doing something wrong. Please help!
That's wrong:
'_serialize' => array($message)
Pay attention to the manual, it shows it correctly in the provided examples.
'_serialize' => array('message')

Yii dropdownlist saving value in ivar onclick

how can I save value as ivar from dropDownlist in yii? here my code, which doesn't work :/
declaration of ivar:
public $blaaa;
and my dropdownlist code:
echo CHtml::dropDownList(
'categoryDropDownList',
'',
CHtml::listData(Category::model()->findAll(), 'id', 'name'),
array(
'empty' => 'Select Category',
'onchange'=>function () {
$this->blaaa = 'js:this.value';
}
));
I tried also with ajax, but it also doesnt work:
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('category/actionBla'),
'data' => array('id' => 'js:this.value')
where
public function bla()
{
if (isset($_POST['id'])) {
$this->blaaa = $_POST['id'];
}
thanks in advance for help!
In ajax section, change url as below
'url' => CController::createUrl('category/bla'),
In controller, your function name should be
public function actionBla()
I solved my problem with echo'ing CHtml::dropDownList in form:
echo CHtml::form();
echo CHtml::dropDownList(
'categoryDropDownList',
'',
CHtml::listData(Category::model()->findAll(), 'id', 'name'),
array(
'empty' => 'Select Category'
));
echo CHtml::endForm();
and now activeForm bother about sending parameters via POST

cakephp HABTM save null field

I have a site develop in cakephp 2.0.
I have a relation HABTM to the same model like this:
class Product extends AppModel {
public $name = 'Product';
public $useTable = 'products';
public $belongsTo = 'User';
public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'ingredients_products',
'foreignKey' => 'product_id',
'associationForeignKey' => 'ingredient_id',
'unique' => false
)
);
}
I want to save a record into my view with a simple form like this:
echo $this->Form->create('IngredientProduct', array ('class' => 'form', 'type' => 'file'));
foreach ($product as $prod) {
echo '<div>'.$prod['ProductAlias']['alias'].'</div>';
echo $this->Form->input('IngredientProduct.product_id', array ('type'=>'text', 'value'=> $prod['ProductAlias']['id'], 'label'=> false, 'id' => 'id'));
}
$select = '<select name="data[IngredientProduct][ingredient_id]" id="[IngredientProductIngredientId">';
foreach ($other_product as $prod2) {
$select .= '<option value="'.$prod2['ProductAlias']['id'].'">'.$prod2['ProductAlias']['alias'].'</option>';
}
$select .= '</select><br>';
echo($select);
echo $this->Form->submit('Collega', array('id'=>'link_product'));
echo $this->Form->end();
Into my controller I save in this mode:
if ($this->Product->saveAll($this->request->data)){
$this->Session->write('flash_element','success');
$this->Session->setFlash ('Prodotto collegato con successo.');
//$this->redirect(array('action'=>'edit',$alias));
}
else{
$this->Session->write('flash_element','error');
$this->Session->setFlash('Errore di salvataggio activity');
}
When I'm going to see into the database I see that ingredient:id is setting well but product_id is 0.
I have debugged my request->data and this is the array:
array(
'IngredientProduct' => array(
'product_id' => '1',
'ingredient_id' => '2'
)
)
I have print the sql query created by cakephp:
INSERT INTO `db`.`ingredients_products` (`product_id`, `ingredient_id`, `modified`, `created`) VALUES ('', 2, '2012-10-09 23:19:22', '2012-10-09 23:19:22')
Why product_id is null instead of 1?
Can someone help me?
Thanks
I think this line is wrong:
$this->Product->saveAll($this->request->data);
Try:
$this->IngredientProduct->saveAll($this->request->data);
as your form seems to ask data for a relationship, not a new product.

Cakephp - search by field of different table

I have two tables:
evaluation_employees
Fields: id, username
evaluation_results
Fields: id, grade, evaluation_employee_id
In evaluation_results view I need to search the results (using the cakephp search plugin) by the employee's username, but in evaluation_results table I have the employee's id(evaluation_employee_id), not the username. I don't know how to make a link between those tables, to make it work.
Code in my view (evaluation_results/index.ctp):
echo $this->Form->create('EvaluationResult', array(
'url' => array_merge(array('action' => 'index'), $this->params['pass'])
));
echo $this->Form->input('username', array('div' => false, 'empty' => true)) . '<br/><br/>';
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();
Code in my controller (evaluation_results_controller.php):
var $components = array('Search.Prg');
function index() {
$this->Prg->commonProcess();
$this->EvaluationResult->recursive = 0;
$this->paginate = array(
'conditions' => $this->EvaluationResult->parseCriteria($this->passedArgs));
$this->set('evaluationResults', $this->paginate());
}
Code in my model (evaluation_result.php):
public $actsAs = array('Search.Searchable');
//Search fields data description for processing.
public $filterArgs = array(
array('name' => 'EvaluationEmployee.username', 'type' => 'query', 'method' => 'filterUsername')
);
//Method as decalred in $filterArgs to process the free form search.
public function filterUsername($data, $field = null) {
if (empty($data['EvaluationEmployee']['username'])) {
return array();
}
$username = '%' . $data['EvaluationEmployee']['username'] . '%';
return array(
$this->alias . '.EvaluationEmployee.username LIKE' => $username
);
}
Please tell me if more info is needed.
If you set up the associations in the model it will find all related records automatically when you search for an employee.
http://book.cakephp.org/1.3/en/view/1039/Associations-Linking-Models-Together

Categories