I want to make update function with 2 where clauses, this is my model code :
function updateJawabanSensus($where,$where1,$data) {
$this->db->where('id_jawaban',$where);
$this->db->where('id_sensus',$where1);
$this->db->update($this->_table, $data);
return $this->db->affected_rows();
}
controller code :
function update_jawaban_sensus() {
$id_jawaban = $this->input->post('id_jawaban', TRUE);
$id_sensus = $this->input->post('id_sensus', TRUE);
$id_keluarga = $this->input->post('id_keluarga', TRUE);
$id_pertanyaan_sensus = $this->input->post('id_pertanyaan_sensus', TRUE);
$jawaban = $this->input->post('jawab_0', TRUE);
$id_indikator = $this->input->post('idInd_0', TRUE);
$indikator = $this->input->post('indikator_0');
$bobot = $this->m_pilihan_jawaban->get_bobot($id_sensus,$jawaban);
$nilai_bobot = $bobot * $indikator;
$data = array(
'id_jawaban' => $id_jawaban,
'id_sensus' => $id_sensus,
'id_indikator' => $id_indikator,
'id_keluarga' => $id_keluarga,
'id_pertanyaan_sensus' => $id_pertanyaan_sensus,
'jawaban' => $jawaban,
'nilai_bobot' => $nilai_bobot
);
//echo json_encode($jawaban);
$result = $this->m_jawaban_sensus->updateJawabanSensus(array('id_jawaban' => $id_jawaban,'id_sensus' => $id_sensus), $data);
redirect('indikatorkesejahteraan/c_jawaban_sensus/konfirmasi/'.$id_sensus.'/'.$id_keluarga);
}
but when i click the update button the data can't change..thanks for your attention
First problem: you are not showing where $this->_table is defined in your model. (I will assume you are setting this in your __construct)
Second problem: your model method expects three parameters: updateJawabanSensus($where,$where1,$data), but you are only sending two:
updateJawabanSensus(array('id_jawaban' => $id_jawaban,'id_sensus' => $id_sensus), $data);
Solution
Codeigniter will accept multiple where clauses in an array. Since you already have an array, just send it once, and permit your model method to accept only two parameters.
Controller:
$arr = array(
'id_jawaban' => $id_jawaban,
'id_sensus' => $id_sensus
);
$this->m_jawaban_sensus->updateJawabanSensus($arr, $data);
Model:
function updateJawabanSensus($where,$data) {
$this->db->where($where);
$this->db->update($this->_table, $data);
return $this->db->affected_rows();
}
Source: http://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data
You are sending only parameter form you controller.
$result = $this->m_jawaban_sensus->updateJawabanSensus(array('id_jawaban' => $id_jawaban,'id_sensus' => $id_sensus), $data);
Instead you using two where condition you can simply do in once.
Model
function updateJawabanSensus($where,$data) {
$this->db->where($where);
$this->db->update($this->_table, $data);
return $this->db->affected_rows();
}
Related
Please help how to update data in a database table without input form. I want to make the value on table become "0". I have created a controller:
function reset(){
$data = array(
'nomor_antrian' => '0',
'jumlah_pengantri' => '0'
);
$this->db->replace('antrian', $data);
}
The model :
function reset($id) {
$data = array(
'nomor_antrian'=>'0',
'jumlah_pengantri'=>'0'
);
$this->db->set($data);
$this->db->where('nomor_loket', $id);
$this->db->update('antrian');
}
and this is the link button in the view section :
Reset
Thanks before.
You have to send $id to update record
Model code
function reset($id){
$data = array(
'nomor_antrian' => '0',
'jumlah_pengantri' => '0'
);
$this->db->set($data);
$this->db->where('nomor_loket', $id);
$this->db->update('antrian');
}
Reset link will be as follow
Reset //$id is a parameter
Pass parameter to reset() function
I am a beginner in CodeIgniter and I want to insert a data in codeigniter with a where clause. Something like a query like this:
insert into tbl_check_up (bill_id) values ("bill_id") where check_up_id = "'.$check_up_id.'" ;
how can i convert it into codeigniter
Here is my codeigniter model:
var $tbl_check_up = 'tbl_check_up';
public function save_bill_checkup($check_up_id,$data) {
$this->db->insert($this->tbl_check_up,$data);
return $this->db->insert_id();
}
Here is my controller :
public function bill_id() {
$check_up_id = $this->input->post('check_up_id');
$data1 = array(
'bill_id' => $bill_id
);
$insert1 = $this->billing_model->save_bill_checkup($check_up_id,$data1);
}
Instead of insert, use update query.
$data = array(
'bill_id' => $bill_id
);
$this->db->where('check_up_id', $check_up_id);
$this->db->update('tbl_check_up ', $data);
I'm new to Laravel and at the moment I have a piece of code in a Controller which without the while loop it works, it retrieves my query from the database.
public function dash($id, Request $request) {
$user = JWTAuth::parseToken()->authenticate();
$postdata = $request->except('token');
$q = DB::select('SELECT * FROM maps WHERE user_id = :id', ['id' => $id]);
if($q->num_rows > 0){
$check = true;
$maps = array();
while($row = mysqli_fetch_array($q)) {
$product = array(
'auth' => 1,
'id' => $row['id'],
'url' => $row['url'],
'locationData' => json_decode($row['locationData']),
'userData' => json_decode($row['userData']),
'visible' => $row['visible'],
'thedate' => $row['thedate']
);
array_push($maps, $product);
}
} else {
$check = false;
}
return response()->json($maps);
}
I am trying to loop through the returned data from $q and use json_decode on 2 key/val pairs but I can't even get this done right.
Don't use mysqli to iterate over the results (Laravel doesn't use mysqli). Results coming back from Laravel's query builder are Traversable, so you can simply use a foreach loop:
$q = DB::select('...');
foreach($q as $row) {
// ...
}
Each $row is going to be an object and not an array:
$product = array(
'auth' => 1,
'id' => $row->id,
'url' => $row->url,
'locationData' => json_decode($row->locationData),
'userData' => json_decode($row->userData),
'visible' => $row->visible,
'thedate' => $row->thedate
);
You're not using $postdata in that function so remove it.
Do not use mysqli in Laravel. Use models and/or the DB query functionality built in.
You're passing the wrong thing to mysqli_fetch_array. It's always returning a non-false value and that's why the loop never ends.
Why are you looping over the row data? Just return the query results-- they're already an array. If you want things like 'locationData' and 'userData' to be decoded JSON then use a model with methods to do this stuff for you. Remember, with MVC you should always put anything data related into models.
So a better way to do this is with Laravel models and relationships:
// put this with the rest of your models
// User.php
class User extends Model
{
function maps ()
{
return $this->hasMany ('App\Map');
}
}
// Maps.php
class Map extends Model
{
// you're not using this right now, but in case your view needs to get
// this stuff you can use these functions
function getLocationData ()
{
return json_decode ($this->locationData);
}
function getUserData ()
{
return json_decode ($this->userData);
}
}
// now in your controller:
public function dash ($id, Request $request) {
// $user should now be an instance of the User model
$user = JWTAuth::parseToken()->authenticate();
// don't use raw SQL if at all possible
//$q = DB::select('SELECT * FROM maps WHERE user_id = :id', ['id' => $id]);
// notice that User has a relationship to Maps defined!
// and it's a has-many relationship so maps() returns an array
// of Map models
$maps = $user->maps ();
return response()->json($maps);
}
You can loop over $q using a foreach:
foreach ($q as $row) {
// Do work here
}
See the Laravel docs for more information.
I am using MySQL as the database connection adapter for all my models. I have a downloads model and controller with an index function that renders either an HTML table or a CSV file depending on the type passed from the request. I also have a CSV media type to handle an array of data, which is working as expected (outputs array keys as headers then array values for each row of data).
I wish to do the same find query but then remove ID fields from the record set if a CSV file is going to be rendered. You'll notice that the download ID is being fetched even though it is not in the fields array, so simply changing the fields array based on the request type will not work.
I have tried the following in the index action of my downloads controller:
<?php
namespace app\controllers;
use app\models\Downloads;
class DownloadsController extends \lithium\action\Controller {
public function index() {
// Dynamic conditions
$conditions = array(...);
$downloads = Downloads::find('all', array(
'fields' => array('user_id', 'Surveys.name'),
'conditions' => $conditions,
'with' => 'Surveys',
'order' => array('created' => 'desc')
));
if ($this->request->params['type'] == 'csv') {
$downloads->each(function ($download) {
// THIS DOES NOT WORK
unset($download->id, $download->user_id);
// I HAVE TRIED THIS HERE AND THE ID FIELDS STILL EXIST
// var_dump($download->data());
// exit;
return $download;
});
return $this->render(array('csv' => $downloads->to('array')));
}
return compact('downloads');
}
}
?>
I thought there was an __unset() magic method on the entity object that would be called when you call the standard PHP unset() function on an entity's field.
It would be great if there was a $recordSet->removeField('field') function, but I can not find one.
Any help would be greatly appreciated.
Perhaps you should do $downloads = $downloads->to('array');, iterate the array with a for loop, remove those fields from each row, then return that array. If you have to do this same thing for a lot of actions, you could setup a custom Media handler that could alter the data without needing logic for it in your controller.
Take a look at this example in the Lithium Media class unit test.
You can also avoid having much logic for it in your controller at all through the use of a custom handler. This example also auto-generates a header row from the keys in your data.
In config/bootstrap/media.php:
Media::type('csv', 'application/csv', array(
'encode' => function($data, $handler, $response) {
$request = $handler['request'];
$privateKeys = null;
if ($request->privateKeys) {
$privateKeys = array_fill_keys($request->privateKeys, true);
}
// assuming your csv data is the first key in
// the template data and the first row keys names
// can be used as headers
$data = current($data);
$row = (array) current($data);
if ($privateKeys) {
$row = array_diff_key($row, $privateKeys);
}
$headers = array_keys($row);
ob_start();
$out = fopen('php://output', 'w');
fputcsv($out, $headers);
foreach ($data as $record) {
if (!is_array($record)) {
$record = (array) $record;
}
if ($privateKeys) {
$record = array_diff_key($record, $privateKeys);
}
fputcsv($out, $record);
}
fclose($out);
return ob_get_clean();
}
));
Your controller:
<?php
namespace app\controllers;
use app\models\Downloads;
class DownloadsController extends \lithium\action\Controller {
public function index() {
$this->request->privateKeys = array('id', 'user_id');
// Dynamic conditions
$conditions = array(...);
$downloads = Downloads::find('all', array(
'fields' => array('user_id', 'Surveys.name'),
'conditions' => $conditions,
'with' => 'Surveys',
'order' => array('created' => 'desc')
));
return compact('downloads');
}
}
?>
Why not then just dynamically set your $fields array?
public function index() {
$type = $this->request->params['type'];
//Exclude `user_id` if request type is CSV
$fields = $type == 'csv' ? array('Surveys.name') : array('user_id', 'Surveys.name');
$conditions = array(...);
$with = array('Surveys');
$order = array('created' => 'desc');
$downloads = Downloads::find('all', compact('conditions', 'fields', 'with', 'order'));
//Return different render type if CSV
return $type == 'csv' ? $this->render(array('csv' => $downloads->data())) : compact('downloads');
}
You can see in this example how I send the array for your CSV handler, otherwise it's the $downloads RecordSet object that goes to the view.
PlanDetails hasMany Companies. PlanDetail table has company_id field.
This is all I need to achieve: PlanDetail.company_id = Company.id. So get all Plan Details where PlanDetail.company_id matches Company.id.
Here is the query I have been messing with in the plan_details_controller:
function pd_list_by_company() {
$this->PlanDetail->unbindModel(array('hasMany' => array('Plan')));
$comp_id = $this->PlanDetail->Company->find('all');
$result = $this->PlanDetails->find('all', array('conditions' => array
('Company.id' => 'PlanDetail.company_id')));
$company_id = $this->PlanDetail->read('company_id');
}
I cannot just get the results I need.. what am I doing wrong here?
Sounds like a simple condition on the company_id field to me:
$this->PlanDetail->find('all', array('conditions' => array('company_id' => $company_id)))
Or, if you want the company as well and your associations are hooked up correctly:
$company = $this->Company->read(null, $company_id);
// echo $company['Company']
// echo $company['PlanDetail'][0], $company['PlanDetail'][1] etc...
You need to get a $company_id to query on from somewhere, which is usually the URL:
public function pd_list_by_company($company_id)
Then visit this action with the URL /plan_details/pd_list_by_company/42, which can be linked to using $this->Html->link('foobar', array('controller' => 'plan_details', 'action' => 'pd_list_by_company', 42)).
Complete example:
public function view($planId) {
$plan = $this->PlanDetail->read(null, $planId);
if (!$plan) {
$this->cakeError('error404');
}
$otherPlansBySameCompany = $this->PlanDetail->find('all', array(
'conditions' => array('company_id' => $plan['PlanDetail']['company_id'])
));
$this->set(compact('plan', 'otherPlansBySameCompany'));
}
I am displaying the set() find result in the Plan Detail view.ctp.
This is how I solved it:
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid plan detail', true));
$this->redirect(array('action' => 'index'));
}
$this->set('planDetail', $this->PlanDetail->read(null, $id));
$cid = $this->PlanDetail->read('Company.id');
$cid_extract = Set::extract($cid, 'Company.id');
$this->set('planComps', $this->PlanDetail->find('all',array('conditions' => array("company_id" => $cid_extract))));
}