Send Data From Controller to View Code Igniter - codeigniter

I have an function get() on my controller. This function I use to get data from database and I save it to $data variable.
It's possible to call get() function on another function and I send the $data variable to the view? I want to make two view, one is classic and another one is modern view.
This is my code:
public function get()
{
$data['all'] = $this->genbamodel->getAll();
$data['delay'] = $this->genbamodel->getDelay();
$data['ontime'] = $this->genbamodel->getOntime();
$data['ahead'] = $this->genbamodel->getAhead();
$data['unloading'] = $this->genbamodel->getUnloading();
$data['topdelay'] = $this->genbamodel->getTopDelay();
$data['topahead'] = $this->genbamodel->getTopAhead();
$data['jumlah'] = count($this->genbamodel->getID())+1;
for ($j=1; $j < $data['jumlah']; $j++) {
$datas['lalax'.$j] = $this->genbamodel->getRecord($j);
$data['lala'.$j] = array_reverse($datas['lalax'.$j]);
}
$data['time'] = $this->genbamodel->getTime();
}
public function home_classic()
{
$this->get();
$this->load->view('home_classic',$data);
}
public function home_modern()
{
$this->get();
$this->load->view('home_modern',$data);
}

Hope this will help you :
Your get() method should return $data
public function get()
{
$data['all'] = $this->genbamodel->getAll();
$data['delay'] = $this->genbamodel->getDelay();
$data['ontime'] = $this->genbamodel->getOntime();
$data['ahead'] = $this->genbamodel->getAhead();
$data['unloading'] = $this->genbamodel->getUnloading();
$data['topdelay'] = $this->genbamodel->getTopDelay();
$data['topahead'] = $this->genbamodel->getTopAhead();
$data['jumlah'] = count($this->genbamodel->getID())+1;
for ($j=1; $j < $data['jumlah']; $j++) {
$datas['lalax'.$j] = $this->genbamodel->getRecord($j);
$data['lala'.$j] = array_reverse($datas['lalax'.$j]);
}
$data['time'] = $this->genbamodel->getTime();
return $data;
}
in home_classic() do it like this
public function home_classic()
{
$data = $this->get();
$this->load->view('home_classic',$data);
}
in home_modern() do the same
public function home_modern()
{
$data = $this->get();
$this->load->view('home_modern',$data);
}
for more : https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view

Related

Sorting League Standings table

Am doing a league management system where the system generates fixtures and assign each match to an official who later enters results. Now when i have set everything possible for the log table but when i pass the results, am getting the some few errors : Too few arguments to function App\Models\Gamescores::updateStandings(), 0 passed in E:\Video\laraVids\laraProjects\HAM\app\Models\Gamescores.php on line 28 and exactly 1 expected
here is my code for the sorting of the league
class Gamescores extends Model
{
use HasFactory;
protected $table = 'gamescores';
protected $fillable = [
'games_id',
'away_score',
'home_score',
];
public function game()
{
return $this->belongsTo(Game::class, 'games_id');
}
public static function boot()
{
parent::boot();
static::created(function ($gamescore) {
$gamescore->updateStandings();
});
}
public function updateStandings($league_id)
{
// Get all gamescores for the specified league
$gameScores = Gamescores::whereHas('game', function ($query) use ($league_id) {
$query->where('league_id', $league_id);
})->get();
// Loop through each gamescore and update the log table for each team
foreach ($gameScores as $gameScore) {
$game = Games::find($gameScore->games_id);
$league_id = $game->league_id;
$home_team_id = $game->home_team;
$away_team_id = $game->away_team;
$home_team_log = Logtable::where('team_id', $home_team_id)->first();
if ($home_team_log !== null) {
$home_team_log->played += 1;
if ($gameScore->home_score > $gameScore->away_score) {
$home_team_log->won += 1;
$home_team_log->points += 3;
} else if ($gameScore->home_score == $gameScore->away_score) {
$home_team_log->drawn += 1;
$home_team_log->points += 1;
} else {
$home_team_log->lost += 1;
}
$home_team_log->goals_for += $gameScore->home_score;
$home_team_log->goals_against += $gameScore->away_score;
$home_team_log->goal_difference = $home_team_log->goals_for - $home_team_log->goals_against;
$home_team_log->save();
}
$away_team_log = Logtable::where('team_id', $away_team_id)->first();
if ($away_team_log !== null) {
$away_team_log->played += 1;
if ($gameScore->away_score > $gameScore->home_score) {
$away_team_log->won += 1;
$away_team_log->points += 3;
} else if ($gameScore->home_score == $gameScore->away_score) {
$away_team_log->drawn += 1;
$away_team_log->points += 1;
} else {
$away_team_log->lost += 1;
}
$away_team_log->goals_for += $gameScore->away_score;
$away_team_log->goals_against += $gameScore->home_score;
$away_team_log->goal_difference = $away_team_log->goals_for - $away_team_log->goals_against;
$away_team_log->save();
}
}
}
}
thats my model where am passing the method to genererate the results
public function fixtureToView($league)
{
// Fetch all rows from the games table, including the related official model
$games = Games::where('league_id', $league)->get();
// Extract the values for the role column as an array
$pluckedFixtures = $games->pluck('Fixture')->toArray();
// Count the number of occurrences of each value in the array
$counts = array_count_values($pluckedFixtures);
// Initialize an empty array to store the duplicate keys and values
$fixtures = collect([]);
// Iterate over the counts array
foreach ($counts as $key => $count) {
// If the count is greater than 1, add the key and value to the duplicates array
$fixtures->push($games->where('Fixture', $key));
}
// In your controller
$gamescores = Gamescores::all();
foreach ($gamescores as $gamescore) {
$game = Games::find($gamescore->games_id);
$league_id = $game->league_id;
$gamescore->updateStandings($league_id);
if($gamescore->games_id){
$game = Games::find($gamescore->games_id);
$league_id = $game->league_id;
$gamescore->updateStandings($league_id);
}
}
$standings = Logtable::all();
$standings = $standings->sortByDesc('points');
// return view('standings', compact('standings'));
return view(
'admin.league.fixtures.index',
compact('fixtures', 'standings')
);
thats my controller where am passing the method to retrieve it in the view, what i want is the log table to get the Id of the league where the games/matches belong to
the error am getting this error

How to get Select max value in codeigniter

Controller:
$next_id = $this->o->next_id();
$data['next_id']=$next_id;
Model:
public function next_id(){
$this->db->select_max('p_ori_id');
$max = $this->db->get('orientation_master');
if($max==0){
$next_id = 1;
}else{
$next_id = 1+$max;
}
return $next_id;
}
Return Error:
Object of class CI_DB_mysqli_result could not be converted to int
Please solve problem..
No offense to #pradeep but you may have some unexpected results if you don't have any rows. I suggest:
public function next_id()
{
$this->db->select_max('p_ori_id', 'max');
$query = $this->db->get('orientation_master');
if ($query->num_rows() == 0) {
return 1;
}
$max = $query->row()->max;
return $max == 0 ? 1 : $max + 1;
}
Hope this will help you:
public function next_id()
{
$this->db->select_max('p_ori_id', 'max');
$query = $this->db->get('orientation_master');
// Produces: SELECT MAX(p_ori_id) as max FROM orientation_master
$max = $query->row()->max;
if($max == 0){
$next_id = 1;
}else{
$next_id = $max+1;
}
return $next_id;
}
For more : https://www.codeigniter.com/user_guide/database/query_builder.html
You are getting that error becuase $max is a result set object and not an integer record value like you're trying to use it.
You can try this function to get the next id.
Modified function:
public function next_id(){
$this->db->select_max('p_ori_id', 'max');
$result = $this->db->get('orientation_master');
$row = $result->row_array();
$next_id = isset($row['max']) ? ($row['max']+1) : 1;
return $next_id;
}
If the column is auto increment, you can use the below code instead.
Alternative:
public function next_id() {
$sql_string = "SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE table_name = '".$this->db->dbprefix."orientation_master'";
$query = $this->db->query($sql_string);
$row = $query->row_array();
return $row['auto_increment'];
}

Strange error session get destroyed

I have a problem when I execute controller method it process controller code but destroy all session including user.
So after process thus controller and I try to open home page, there is no logged in account.
I'm sure no destroy session code, nor logout code in my controller. and I can say this is not about session expired.
I don't know what wrong is this about code, yii2 configuration or logic, but is someone have similar problem in past?
Hope you can guide me to solve this problem.
If you need more information, please let me know.
This not related to code maybe, but here is my controller code.
<?php
namespace frontend\controllers;
use Yii;
use common\models\TbCustomer;
use yii\web\Controller;
use common\models\Model;
use common\models\VwProdukAgent;
use common\models\TbCart;
use yii\helpers\VarDumper;
use common\models\VwProduk;
use yii\data\ActiveDataProvider;
use common\models\VwProdukCustomer;
use common\models\TbCustomerShipment;
use common\component\BeoHelper;
use common\models\TbProdukEkspedisi;
use common\models\TbKota;
use yii\helpers\Url;
/**
* CustomerController implements the CRUD actions for TbCustomer model.
*/
class Pengiriman1Controller extends Controller
{
public function beforeAction($action)
{
Yii::$app->timeZone = 'Asia/Jakarta';
if(Yii::$app->user->isGuest)
{
//$url = Url::to([['home'],'message'=>'Anda Harus Login Terlebih Dahulu']);
\Yii::$app->getSession()->setFlash('message', \Yii::t('app', 'Anda Harus Login Terlebih Dahulu'));
$this->goHome();
return FALSE;
}
//if ($action->id == 'my-method') {
$this->enableCsrfValidation = false;
// }
return parent::beforeAction($action);
}
public function actionIndex()
{
//get alamat customer
//$lsalamat = array();
if(!\Yii::$app->user->isGuest)
{
BeoHelper::refreshCart();
//cek cart kosong atau tidak
if(isset(\Yii::$app->session['produkcart']))
{
$lsproduk = \Yii::$app->session['produkcart'];
if (count($lsproduk)<1)
{
\Yii::$app->getSession()->setFlash('message',"silahkan berbelanja terlebih dahulu");
return $this->redirect(Url::to(['cart/index']));
}
}
$customer_id = Yii::$app->user->id;
$message = '';
$model = null;
if(\Yii::$app->request->post('opsi_alamat',null)!=null)
{
$opsi_pengiriman = \Yii::$app->request->post('opsi_alamat',null);
//return $opsi_pengiriman;
if($opsi_pengiriman == 'new')
{
$model = new TbCustomerShipment();
$model->load(Yii::$app->request->post());
$model->customer_id = $customer_id;
if($model->save())
{
\Yii::$app->session['shipemenadd'] = $model;
//get kurir preselected
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where(['produk_id' => $produk->produk_id])->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $model->kota_id ")->one();
$berat_produk = $produk->kuantitas *$produk->berat_produk;
$berat_produk = round($berat_produk);
$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $berat_produk, $kode,$service,$produk->produk_id);
if(count($result)!=0)
{
$produk->harga_kurir = $result[0]['value'];
$produk->estimasi_sampai = $result[0]['etd'];
}
else
{
$message = "pilihan kurir untuk lokasi tersebut tidak tersedia";
}
//return VarDumper::dump($result);
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
if(isset(Yii::$app->session['shipemenadd'])){
return "exists";
}else{
return "doesn't exist";
}
//return $this->redirect(['pengiriman2/index','message'=>$message]);
//print_r(Yii::$app->session['shipemenadd']);
}
//else
//{
// VarDumper::dump($model);
//}
}
else
{
$pengiriman_selected = TbCustomerShipment::find()->where("customer_shipment_id = $opsi_pengiriman")->one();
\Yii::$app->session['shipemenadd'] = $pengiriman_selected;
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where("produk_id =$produk->produk_id")->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
//get kota id rajaongkir
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $pengiriman_selected->kota_id ")->one();
//$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $produk->berat_produk, $kode,$service);
//return VarDumper::dump($result);
//if(count($result)!=0)
//{
//$produk->harga_kurir = $result[0]['value'];
//$produk->estimasi_sampai = $result[0]['etd'];
$produk->harga_kurir = 0;
$produk->estimasi_sampai = 0;
//}
//else
//{
// $message = "pilihan kuriri untuk lokasi tersebut tidak tersedia";
//}
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
return $this->redirect(['pengiriman2/index','message'=>$message]);
}
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
if(count($lsalamat)==0)
//insert to tb shipment
{
$datacustomer = TbCustomer::find()->where(['customer_id'=>$customer_id])->one();
$newalamat = new TbCustomerShipment();
$newalamat->customer_id = $customer_id;
$newalamat->kota_id = $datacustomer->kota_id;
$newalamat->kecamatan_id = $datacustomer->kecamatan_id;
$newalamat->negara_id = $datacustomer->negara_id;
$newalamat->propinsi_id = $datacustomer->propinsi_id;
$newalamat->alamat = $datacustomer->alamat;
$newalamat->shipment_name = "Alamat Rumah";
$newalamat->penerima = $datacustomer->nama;
$newalamat->hp_penerima = $datacustomer->hp;
$newalamat->save();
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
return $this->render('index',['lsalamat'=>$lsalamat,'newalamat'=> $model]);
}
else
{
return $this->goHome();
}
}
}
here is the problem
\Yii::$app->session['shipemenadd'] = $model;
it should
$currentTbCustomerShipment = TbCustomerShipment::find()->where(['customer_user_id' => $model->customer_user_id])->one(); //find latest object
Yii::$app->session['shipemenadd'] = $currentTbCustomerShipment;

Laravel Query Builder dynamic nested where/orWhere

I hope someone can help guide me in the right direction. I am new to Laravel and far from the best php coder. I am trying to build dynamic nested where/orWhere clauses and I am stuck, and by stuck I mean I can't figure it out. The code I have so far is:
public static function runNested($rId, $current_id) {
$insidestuff = DB::table('tableName')
->select('all fields necessary')
...
->get();
$count=1;
foreach ($insidestuff as $inside)
{
$var1 = $inside->var1;
$var2 = $inside->var2;
$var3 = $inside->var3;
$var4 = $inside->var4;
if ($count == 1)
{
$outsideMet = $outsideMet->where(function($query) use ($var1, $var2, $var3, $var4, $id)
{
$query->where($var1, $var2, $var3);
$outsideMet = myClass::runNested($var4, $id);
});
} else {
$outsideMet = $outsideMet->orWhere(function($query) use ($var1, $var2, $var3, $var4, $id)
{
$query->where($var1, $var2, $var3);
$outsideMet = myClass::runNested($var4, $id);
});
}
$count++;
}
}
public static function runOutside($rId) {
$outsideQuery = DB::table('tableName')
->select('all necessary fields')
->get();
$outsideMet = dbTable::select('*');
$outsideMet = $outsideMet->leftJoin('necessary fields');
$outsideCount=1;
foreach ($oursideQuery as $oQuery)
{
$oVar1 = $oQuery->oVar1;
$oVar2 = $oQuery->oVar2;
$oVar3 = $oQuery->oVar3;
$oVar4 = $oVar4;
$oVar5 = $oQuery->oVar5;
if ($outsideCount == 1)
{
$outsideMet = $outsideMet->where(function($query) use ($oVar1, $oVar2, $oVar3, $oVar4, $oVar5)
{
$query->where($oVar1, $oVar2, $oVar3);
$outsideMet = myClass::runNested($oVar4, $oVar5);
});
} else {
$outsideMet = $outsideMet->orWhere(function($query) use ($oVar1, $oVar2, $oVar3, $oVar4, $oVar5)
{
$query->where($oVar1, $oVar2, $oVar3);
$outsideMet = myClass::runNested($oVar4, $oVar5);
});
}
$outsideCount++;
}
$outsideMet = $outsideMet->count();
I hope someone can tell me how to do this properly, and if the above code is even close, what I am doing wrong. Thank you in advance for the help and guidance.

Codeigniter: How to declare a global variable for a recursive function, and how to return it?

I want to use recursion in a model in Codeigniter, and am baffled as to where I should declare the global variable to be used in the recursive function.
I'm trying to show a catalog of products, ordered by their geographical classification. The recursion is needed because the geographical database is a hierarchy tree, where a place can have sons, grandsons, great-grandsons etc (for example: London is the son of England, which is the son of Britain, which is the son of Europe).
At the end of the recursion, I want to return the variable $arrCatalog, which will hold all the products. So my other question is how to return that variable in the end?
Here is my code (not tested yet, because I didn't know how to handle the global variable):
class Catalogs_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
function getCatalog($place_id, $prod_type)
{
$sql =
"SELECT id, heb_name, type FROM places p
INNER JOIN places_relations r ON p.id = r.son
WHERE father = ?
ORDER BY sort_name";
$query = $this->db->query($sql, $place_id);
if($query->num_rows() > 0) {
foreach ($query->result() as $place) {
$sql2 =
"SELECT code, heb_title, price, place_id FROM products
INNER JOIN products_places ON prod_code=code
WHERE place_id = ? AND prod_type = ?";
$query2 = $this->db->query($sql, $place_id, $prod_type);
if($query2->num_rows() > 0) {
foreach ($query2->result() as $product) {
$arrCatalog[] = $product; // $arrCatalog is the global variable I don't know where to declare and how to return.
}
$this->getCatalog($place['id'], $prod_type);
}
}
}
}
}
Pass your variable to the current object ($this), then you can pass it around your model or hand it to a controller.
class Catalogs_model extends CI_Model {
public $arrCatalog = array();
public function __construct() {
parent::__construct();
}
function getCatalog($place_id, $prod_type) {
$sql = "SELECT ...";
$query = $this->db->query($sql, $place_id);
if($query->num_rows() > 0) {
foreach ($query->result() as $place) {
$sql2 = "...";
$query2 = $this->db->query($sql, $place_id, $prod_type);
if($query2->num_rows() > 0) {
foreach ($query2->result() as $product) {
$this->arrCatalog[] = $product;
}
$this->getCatalog($place['id'], $prod_type);
}
}
}
}
Your controller:
$this->catalogs_model->getCatalog(2, 'hebBook');
$data['data_rows'] = $this->catalogs_model->arrCatalog;
Testing, alter your model like so ....
class Catalogs_model extends CI_Model {
public $arrCatalog = array();
// add these variables for testing ....
private $greeting = 'Hello'; // notice this is private? You cannot access this from your controller but you can from anywhere within the Catalogs_model class.
public $output = ''; // public
public $string = null; // public
// your existing code ...
function hello ()
{
$this->output = $this->greeting;
}
function hello_string ()
{
if($this->string)
{
$this->output = $this->greeting.' '.$string;
}
}
} // end class
Now test in your controller
$this->catalogs_model->hello(); // runs the hello function which sets the model->output
echo $this->catalogs_model->output; // echos 'Hello'
echo '<br />'; // just so the output stands apart in your browser.
$this->catalogs_model->string = 'World!';
$this->catalogs_model->hello_string();
echo $this->catalogs_model->output; // echos Hello World!

Resources