How to pass variable $data to controller? - codeigniter

I've no idea to pass $data variable from Model to Controller.
In Model:
function active(){
$query = $this->db->query(" SELECT * FROM `event` WHERE DATE_FORMAT( NOW( ) , '%m-%d-%Y' ) BETWEEN START AND END ");
foreach($query->result_array() as $row){
$ev_name = $row['ev_name'];
$image = $row['ev_image'];
$start = $row['start'];
$end = $row['end'];
$desc = $row['ev_dec'];
$ev_id = $row['ev_id'];
}
$data = array('ev_name' => $ev_name,
'ev_image' => $image,
'start' => $start,
'end' => $end,
'ev_desc' =>$desc,
'ev_id'=> $ev_id
);
echo $data;
}
In Controller:
function active_event()
{
$this->load->view('active_event');
$this->load->model('Usermodel', Sdata);
}

You should use return keyword which is used for passing data from one function to another. You also need to load and call model method before loading view so that you can use data from modal in view. I think you need to check MVC pattern and Codeigniter userguide.
In your model,
function active(){
$query = $this->db->query(" SELECT * FROM `event` WHERE DATE_FORMAT( NOW( ) , '%m-%d-%Y' ) BETWEEN START AND END ");
foreach($query->result_array() as $row){
$ev_name = $row['ev_name'];
$image = $row['ev_image'];
$start = $row['start'];
$end = $row['end'];
$desc = $row['ev_dec'];
$ev_id = $row['ev_id'];
}
$data = array('ev_name' => $ev_name,
'ev_image' => $image,
'start' => $start,
'end' => $end,
'ev_desc' =>$desc,
'ev_id'=> $ev_id
);
return $data;
}
In your controller,
function active_event()
{
$this->load->model('YOUR MODEL NAME');
$data = $this->YOURMODELNAME->active();
$this->load->view('active_event', $data);
}

Related

how to insert the data using codeiginter?

I am new to codeiginter,how to insert the data into table using codeiginter
my controller code;
$data = array(
'subgrpname' => $this->input->post('subgrpname'),
'grpname'=> $this->input->post('grpname'),
'pltype'=> $this->input->post('pltype')
);
It is simple form use internet to search it
$data = array(
'subgrpname' => $this->input->post('subgrpname'),
'grpname'=> $this->input->post('grpname'),
'pltype'=> $this->input->post('pltype')
);
$this->db->insert('tablename',$data);
I would like to share reusable code approach by following the MVC coding style
My Controller
$table = 'table_name';
$data = array(
'subgrpname' => $this->input->post('subgrpname'),
'grpname'=> $this->input->post('grpname'),
'pltype'=> $this->input->post('pltype')
);
$record_id = $this->Common_Model->insert_into_table($table, $data);
My Common_Model
function insert_into_table($table, $data) {
// echo "<pre>";print_r($data);exit;
$insert = $this->db->insert($table, $data);
$insert_id = $this->db->insert_id();
if ($insert) {
return $insert_id;
} else {
return false;
}
}
You can use this model function as much time as you want.

Cannot Update On Laravel 5.5

I get problem.
This is my controller
public function finish(Request $request)
{
$result = $request->input('data');
//$data = json_decode($result, true);
return $this->InvoiceBayar($result);
}
public function InvoiceBayar($result)
{
$data = json_decode($result, true);
$transaction = $data['transaction_status'];
$type = $data['payment_type'];
$order_id = $data['order_id'];
$fraud = $data['fraud_status'];
Fee::where('invoice',$order_id)
->update([
'status' => 'Paid',
]);
echo "Transaction order_id: " . $order_id ." successfully transfered using " . $type;
}
This is my Route
Route::POST('/notification', 'SnapController#finish');
When Payment gateway, send a parameter to me, I cannot update DB.
But when I use POSTMAN. I success update DB
You need to use $request->all() as it will contain all payment gateway data.
public function finish(Request $request)
{
$result = $request->all();
return $this->InvoiceBayar($result);
}
Alternately you can do this
$update = Fee::where('invoice',$order_id)->first();
$update->status = 'Paid';
$update->save();
You should try this:
public function InvoiceBayar($result)
{
$data = json_decode($result, true);
$transaction = $data->transaction_status;
$type = $data->payment_type;
$order_id = $data->order_id;
$fraud = $data->fraud_status;
Fee::where('invoice',$order_id)
->update([
'status' => 'Paid',
]);
echo "Transaction order_id: " . $order_id ." successfully transfered using " . $type;
}

Yii: save multiple records in one query

I'm trying to save a lot of CActiveRecord model objects in a loop.
I have something like this:
foreach ($array_of_items as $item) {
$values = array(
"title" => $item->title,
"content" => $item->content,
);
$object = new MyModel;
$object->attributes = $values;
$object->save();
}
In my case, this creates about 400 CActiveRecord objects. The saving process is really slow, because each save() queries the database.
Is there a way to save all those objects in one go?
Something like:
$objects = array();
foreach ($array_of_items as $item) {
$values = array(
"title" => $item->title,
"content" => $item->content,
);
$object = new MyModel;
$object->attributes = $values;
$objects[] = $object;
}
save_all_objects($objects);
I could not find anything on the subject. Anyone?
you can validate() your model, and if it was ok you can append it so a sql text for insert,
and after your loop, just use databases commandBuilder() and execute your prepared text
$sql = '';
if($object->validate())
{
$sql .= ',("' . $object->attr1 . '")'// append to script,(you get the idea, you need to also make a correct values)
}
...
if(!empty($sql))
{
$sql = 'INSERT INTO table (attr1) Values' . $sql;// make complete script
// execute that command
}
Since v1.1.14, the method createMultipleInsertCommand() of CDbCommandBuilder class is available.
For insert multi rows, Put this code in components folder under GeneralRepository.php file name.
<?php
class GeneralRepository
{
/**
* Creates and executes an INSERT SQL statement for several rows.
* By: Nabi K.A.Z. <www.nabi.ir>
* Version: 0.1.0
* License: BSD3
*
* Usage:
* $rows = array(
* array('id' => 1, 'name' => 'John'),
* array('id' => 2, 'name' => 'Mark')
* );
* GeneralRepository::insertSeveral(User::model()->tableName(), $rows);
*
* #param string $table the table that new rows will be inserted into.
* #param array $array_columns the array of column datas array(array(name=>value,...),...) to be inserted into the table.
* #return integer number of rows affected by the execution.
*/
public static function insertSeveral($table, $array_columns)
{
$connection = Yii::app()->db;
$sql = '';
$params = array();
$i = 0;
foreach ($array_columns as $columns) {
$names = array();
$placeholders = array();
foreach ($columns as $name => $value) {
if (!$i) {
$names[] = $connection->quoteColumnName($name);
}
if ($value instanceof CDbExpression) {
$placeholders[] = $value->expression;
foreach ($value->params as $n => $v)
$params[$n] = $v;
} else {
$placeholders[] = ':' . $name . $i;
$params[':' . $name . $i] = $value;
}
}
if (!$i) {
$sql = 'INSERT INTO ' . $connection->quoteTableName($table)
. ' (' . implode(', ', $names) . ') VALUES ('
. implode(', ', $placeholders) . ')';
} else {
$sql .= ',(' . implode(', ', $placeholders) . ')';
}
$i++;
}
$command = Yii::app()->db->createCommand($sql);
return $command->execute($params);
}
}
And usage anywhere:
$rows = array(
array('id' => 1, 'name' => 'John'),
array('id' => 2, 'name' => 'Mark')
);
GeneralRepository::insertSeveral(User::model()->tableName(), $rows);
https://www.yiiframework.com/extension/yii-insert-multi-rows

How to get parameters in JFormField from a disabled plugin in Joomla 1.6/2.5?

How i can get some parameters from a disabled/not yet actived plugin in joomla 1.6/2.5?
$module = JPluginHelper::getPlugin('system','myplugin');
$moduleParams = new JParameter($module->params);
$val = $moduleParams->get("key");
This method didn't work becouse i need to use within an element JFormField generator.
Thanks for help!
With JPluginHelper::getPlugin it's possible to access only enabled plugins, so here's the code for direct access to database.
// Build query
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select( 'params' )
->from( '#__extensions' )
->where( 'type = ' . $db->q('plugin') )
->where( 'folder = ' . $db->q('authentication') ) // Plugin type
->where( 'element = ' . $db->q('gmail') ) // Plugin element
;
// Execute query
$db->setQuery($query);
try
{
$result = $db->loadResult();
}
catch (RuntimeException $e)
{
return false;
}
// Parse parameters
if (!empty($result))
{
$params = new JRegistry($result);
$val = $params->get('key', 'defaultValue');
}
You may store query results in in the JFormField Object so save database queries in case field is availabile multiple times.
protected $results = null;
Perhaps you may want to try this:
// Get plugin parameters
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('`params`')
->from ('`#__extensions`')
->where ("`type` = 'plugin'")
->where ("`folder` = 'system'")
->where ("`element` = 'myplugin'");
$db->setQuery($query);
$res = json_decode($db->loadResult(), true);
$val = $res['key'];
Just find the answer by myself.
$data = null;
foreach ((array) $this->form as $k => $v) {
if($val instanceof JRegistry){
$data = &$v;
break;
}
}
$data = $data->toArray();
$val = $data['params']['key'];
Thanks! Bye!

codeigniter error using JOIN to select single row

Im trying to get joins to work when selecting a single row. here is my code:
model:
function view($id) {
$this->db->select('c.name
,c.phone
,c.active
,c.website
,c.date_acquired
,con.firstName');
$this->db->from('company c');
$this->db->join('contacts con','c.primary_contact = con.id','left');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->row_array();
controller:
public function view($id)
{
$this->load->model('Company_model');
$data['data']= $this->Company_model->view($id);
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
the error im getting is:
Fatal error: Call to a member function row_array() on a non-object in
/home/techf/public_html/application/models/company_model.php on line
35
and line 35 in the above code is:
$query = $this->db->get()
is this not correct when dealing with joins and a row array?
**
edit 1
**:
Here is my controller:
public function view($id)
{
$this->load->model('Company_model');
$data = $this->Company_model->view($id)->row();
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
and my model:
function view($id) {
$this->db->select('*');
$this->db->from('company');
$this->db->join('contacts con','c.primary_contact = con.id','left');
$this->db->where('id', $id);
return $this->db->get('company');
}
but now im am getting error:
Fatal error: Call to a member function row() on a non-object in
/home/techf/public_html/application/controllers/company.php on line 21
Here you go model code
public function get_joins($table,$value,$joins,$where,$order_by,$order)
{
$this->db->select($value);
if (is_array($joins) && count($joins) > 0)
{
foreach($joins as $k => $v)
{
$this->db->join($v['table'], $v['condition'], $v['jointype']);
}
}
$this->db->order_by($order_by,$order);
$this->db->where($where);
return $this->db->get($table);
}
and in your controller aceess it like
$value=('restaurantorders.*,restaurant.Name,restaurant.CurrencyId,currency.*,orderpaymentdetail.Gateway ');
$joins = array
(
array
(
'table' => 'tk_restaurant',
'condition' => 'restaurant.Id = restaurantorders.RestaurantId',
'jointype' => 'inner'
),
array
(
'table' => 'tk_currency',
'condition' => 'restaurant.CurrencyId = currency.Id',
'jointype' => 'inner'
),
array
(
'table' => 'tk_orderpaymentdetail',
'condition' => 'restaurantorders.Id = orderpaymentdetail.OrderId',
'jointype' => 'inner'
),
);
$data['order_detail'] = $this->general_model->get_joins($data['tbl'],$value,$joins,array('OrderStatus'=>'Confirm','restaurantorders.Id'=>$orderid),'restaurantorders.Id','desc')->row();
note that on the model i test first if num_rows() is greater than 1 before sending on the row and if not return false.
Note that on my this->db->get i removed the name of the table, because you already added it on the from method.
$this->db->select('*')
->from('company c');
->join('contacts con','c.primary_contact = con.id','left');
->where('id', $id);
$query = $this->db->get();
return $query->num_rows() >= 1 ? $query->row() : FALSE;
on your COntroller
on on the data variable you forgot to add a key, this will be used when you access the variable/object on you're view, example is $data['contacts']
public function view($id)
{
$this->load->model('Company_model');
$data['contacts'] = $this->Company_model->view($id);
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
on your VIEWS
access the contacts key that you assigned earlier on you're controller.
<?
if(!empty($contacts))
{
print_r($contacts);
}else{
echo 'No data';
}
?>
to show the structure of your query on a standard MySQL query
you could comment out the return on you're model and add this snippets of code just after the $this->db->get() method.
echo $this->db->last_query();
die();
This will echo out what query was made, and you can run it on phpmyadmin and compare if the values returned are right.
can you try it like this maybe?
model: (i'm not sure in which table is id and in which primary_contact, so change that if i made a mistake)
function view($id) {
$this->db->join('contacts','company.primary_contact = contacts.id','left')
->where('id', $id);
$query = $this->db->get('company');
return $query->row();
}
in controller call it like this:
$data['result'] = $this->company_model->view($id);
then access object in view:
<?=$result->id?> (etc.)

Resources