Issue passing data from an array to another array in codeigniter - php

i have a problem on passing data result to another data request in a controller in codeigniter is there something i'm missing ?
Controller method :
public function index()
{
//sending $data array of variables to view's or to model's
$data = array('header_title' => 'Nova Democracia - Eleições 2019 - Menu');
$data['formData'] = $this->Crud_model->getProvinciaAndLocal($this->session->id_local);
$data['locais'] = $this->Crud_model->getLocaisByIdLocal($formData["id_distrito"]);
$this->load->view("form_menu/form_menu.php", $data);
}
and my model methods :
function getProvinciaAndLocal($id_local){
$query = $this->db->query("SELECT `nome_local`, `nome_provincia`, tb_local.id_distrito
FROM `tb_user`
INNER JOIN `tb_local`
ON tb_user.id_local = tb_local.id_local
INNER JOIN `tb_distrito`
ON tb_local.id_distrito = tb_distrito.id_distrito
INNER JOIN `tb_provincia`
ON tb_distrito.id_provincia = tb_provincia.id_provincia
WHERE tb_user.id_local = '".$id_local."' ");
$row = $query->row();
$obj = array(
'nome_provincia' => $row->nome_provincia,
'nome_local' => $row->nome_local,
'id_distrito' => $row->id_distrito
);
return $obj;
}
function getLocaisByIdLocal($id_distrito){
$query = $this->db->query("SELECT tb_local.id_local, `nome_local`
FROM `tb_user`
INNER JOIN `tb_local`
ON tb_user.id_local = tb_local.id_local
INNER JOIN `tb_distrito`
ON tb_local.id_distrito = tb_distrito.id_distrito
INNER JOIN `tb_provincia`
ON tb_distrito.id_provincia = tb_provincia.id_provincia
WHERE tb_local.id_distrito = '".$id_distrito."' ");
$row = $query->row();
$obj = array(
'id_local' => $row->id_local,
'nome_local' => $row->nome_local,
);
return $obj;
}
Is there something im doing wrong? Because when i use $formData["nome_provincia"] in the view it works well..

Change your controller like this.
public function index()
{
//sending $data array of variables to view's or to model's
$data = array('header_title' => 'Nova Democracia - Eleições 2019 - Menu');
$data['formData'] = $this->Crud_model->getProvinciaAndLocal($this->session->id_local);
$data['locais'] = $this->Crud_model->getLocaisByIdLocal($data['formData']["id_distrito"]); // Notice the change here
$this->load->view("form_menu/form_menu.php", $data);
}

Related

CakePHP custom query paginator: custom paginate function is not called

I build a custom query and tried use the default paginator, like this:
WodsController.php
$userId = $this->Auth->user('id');
$connection = ConnectionManager::get('default');
$result = $connection->execute("SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods
LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc limit 50")->fetchAll('assoc');
$results = array();
foreach ($result as $r) {
$entity = $this->Wods->newEntity($r);
array_push($results, $entity);
}
$wods = $this->paginate($results);
$this->set('_serialize', ['wods']);
I got this error "Unable to locate an object compatible with paginate".
Now I'm tryng implement custom query paginator, but it's not working.
I implemented paginate and paginateCount functions in the model.
Wods.php file:
public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
$recursive = -1;
$this->useTable = false;
$sql = '';
$sql .= "SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc limit ";
// Adding LIMIT Clause
$sql .= (($page - 1) * $limit) . ', ' . $limit;
$results = $this->query($sql);
return $results;
}
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$sql = '';
$sql .= "SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc";
$this->recursive = $recursive;
$results = $this->query($sql);
return count($results);
}
In the controller WodsController.php
public function index()
{
$this->Wods->recursive = 0;
$this->paginate = array('Wods'=>array('limit'=>10));
$this->set('wods', $this->paginate('Wods'));
}
But the custom paginator is not called, it continues calling the default paginate function. Why ?
Following dragmosh advise (thanks), I investigate CakePHP ORM custom queries builder.
In this solution I used find() function with specific options, after I called the default paginator:
$query = $this->Wods->find()
->select(['Wods.id', 'Wods.titulo','Wods.dia','Wods.rounds','Wods.tempo','Wods.repeticoes','Userwods.user_id'])
->join([
'table' => 'Userwods',
'alias' => 'Userwods',
'type' => 'LEFT',
'conditions' => 'Userwods.wod_id = Wods.id',
])
->where(function ($exp, $q) {
return $exp->isNull('Userwods.user_id');})
->orWhere(['Userwods.user_id' => 4])
->contain(['Userwods'])
->autoFields(true);
$wods = $this->paginate($query);
$this->set(compact('wods'));
$this->set('_serialize', ['wods']);

Correct way to display my query

I have a query in my model that I need to print the data in my view
Model
function get_bank()
{
$query = $this->db->query("SELECT
(
12* (YEAR('account_add_date') - YEAR('start_date')) +
(MONTH('account_add_date') - MONTH('start_date'))
) AS differenceInMonth
->FROM ('bank')
WHERE mem_id = '".$this->session->userdata('id')."'");
return $query->result();
$data['account_age'] = $query->row_array();
}
and I am trying to print the output in my model, but its not working and I do not know where I have gone wrong. I am new to MVC and still getting used to it.
View
<h2>age of account</h2>
<?php
$age = $this->model('profiles_model' , $data );
print "<h2>$age</h2>";
?>
Controller
function index()
{
$data = array();
$this->load->model('user_profile/profiles_model');
$query = $this->profiles_model->get_bank();
if(!empty($query))
{
$data['records'] = $query;
}
$this->load->view('profile_view', $data);
}
Let's first write your code in proper convention.
Model
function get_bank() {
$mem_id = $this->session->userdata('id');
$query = $this->db
->select("12*(YEAR('account_add_date') - YEAR('start_date')) + (MONTH('account_add_date') - MONTH('start_date')) AS differenceInMonth")
->where('mem_id', $mem_id)
->get('bank');
return $query;
// $data['account_age'] = $query->row_array(); <-- Statement after return is useless.
}
Controller
function index() {
$data = array(
'records' => array()
);
$this->load->model('user_profile/profiles_model');
$bank = $this->profiles_model->get_bank();
if($bank->num_rows()){
$data['records'] = $bank->row_array();
}
$this->load->view('profile_view', $data);
}
View
Not sure what you are trying to do with the bank data but here's how you print the record
<p>Bank data</p>
<p><?=isset($records['differenceInMonth'])?$records['differenceInMonth']:"No record found"?></p>
You are not far away, do it this way:
Controller:
function index()
{
$this->load->model('user_profile/profiles_model');
$data = $this->profiles_model->get_bank();
$this->load->view('profile_view', $data);
}
Model:
function get_bank()
{
$query = $this->db->query("SELECT
(
12* (YEAR('account_add_date') - YEAR('start_date')) +
(MONTH('account_add_date') - MONTH('start_date'))
) AS differenceInMonth
->FROM ('bank')
WHERE mem_id = '".$this->session->userdata('id')."'");
return $query->result();
}
View:
<?php
foreach(differenceInMonth AS $age){
echo "<p>" . $age . "</p>";
}
When you load the view you are passing in $data with $data['records'] that has the data you are wanting to display.
Since that is how you pass the data into the view when you load it you will need to call it that way:
<?php
var_dump($records);
?>
You will also need to loop through the data as well assuming $records is an array of the query results or use var_dump instead of print just to verify the data is there.
Reading through these will help going forward:
https://codeigniter.com/user_guide/general/views.html
https://codeigniter.com/user_guide/general/models.html

How to return multiple results in a php function

I have the following function that aims to fetch all credits from an artist for a particular song using the ID from the url ($id), and a foreach statement that displays the information on the Web page. At the moment it's displaying the artist names fine, but the IDs aren't being displayed. How would I go about returning the ID information so it's displayed as well?
function getArtistsBySongId($id)
{
$query = "SELECT * FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
LEFT OUTER JOIN `Song` AS s ON s.song_id = c2a.song_id
LEFT OUTER JOIN `Project` AS p ON p.project_id = s.project_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$artists = Array();
$artisttoid = Array();
$songtoid = Array();
while( $row = mysql_fetch_array($res) ) {
$artist = $row[artist_name];
$credit = $row[credit_name];
$songcr = $row[song_id];
if(!array_key_exists($artist, $artists) ) {
$artists[$artist] = Array();
$artisttoid[$artist] = $row[artist_id];
$songtoid[$songcr] = $row[song_id];
}
$artists[$artist][] = $credit;
}
return $artists;
return $songtoid;
return $artisttoid;
}
I've used include's in the code because I'm still green to PHP and find it easier to understand.
<table border="0" cellspacing="5" cellpadding="5" class="cdinfo" width="100%;">
<tr>
<?php
if (getArtistsBySongId($id) == NULL) {
echo "<th style='font-size: 13px'>Credits:</th>";
echo "<td style='font-size: 13px'>There are currently no artists linked to this song.</td>";
} else {
include 'songs/getsongcredits.php';
}
?>
</tr>
</table>
songs/getsongcredits.php
<?php foreach (getArtistsBySongId($id) as $artist => $creditarr) {
$credits = implode( ", ", $creditarr );
echo "<a href='star.php?id={$artisttoid[$artist]}'>{$artist}</a> ({$credits})<br />";
} ?>
Objects or arrays are the way to do it
return array('artists' => $artists, 'songtoid' => $songtoid, 'artisttoid' => $artisttoid);
I recomend you to return an object with each item you want in attributes.
To return an object, firstly you need a class:
class MyClass {
private $artists;
private $songtoid;
private $artisttoid;
public function __construct($arg1, $arg2, $arg3){
$this->artists = $arg1;
$this->songtoid = $arg2;
$this->artisttoid = $arg3;
}
public function getArtists(){return $this->artists;}
public function getSongtoid(){return $this->songtoid;}
public function getArtisttoid(){return $this->artisttoid;}
}
In your function
function getArtistsBySongId(){
...
return new MyClass($artists, $songtoid, $artisttoid);
}
Also you can return an associative array like this
return array(
"artists"=>$artists,
"songtoid"=>$songtoid,
"artisttoid"=>$artisttoid
);
Or, if you want, you can return an array (as Machavity answered) and read the result using list()
function getArtistsBySongId(){
...
return array($artists, $songtoid, $artisttoid);
}
list($artists, $songtoid, $artisttoid) = getArtistsBySongId();

Query array on model codeigninter

I am a student who learns CodeIgniter, I have a school assignment about the database, I create a project, and run query in my model just like this.
class Send_model extends CI_Model{
function hello(){ $table = $this->db->query("SELECT * FROM (`tbl1`) LEFT JOIN `tbl2` ON `tbl2`.`id` = `tbl1`.`child_id` LEFT JOIN `tbl3` ON `tbl3`.`id` = `tbl1`.`child_id` ");
foreach($table->result() as $row){
$modbus[]= $row->modbus;
$data []= $row->data;
$alert[]= $row->alert;
};
$param0 = '&'.$modbus[0].'='.$data[0].':'.$alert[0];
$param1 = '&'.$modbus[1].'='.$data[1].':'.$alert[1];
$param2 = '&'.$modbus[2].'='.$data[2].':'.$alert[2];
$param3 = '&'.$modbus[3].'='.$data[3].':'.$alert[3];
$param4 = '&'.$modbus[4].'='.$data[4].':'.$alert[4];
$param5 = '&'.$modbus[5].'='.$data[5].':'.$alert[5];
$param6 = '&'.$modbus[6].'='.$data[6].':'.$alert[6];
$param7 = '&'.$modbus[7].'='.$data[7].':'.$alert[7];
$param8 = '&'.$modbus[8].'='.$data[8].':'.$alert[8];
$param9 = '&'.$modbus[9].'='.$data[9].':'.$alert[9];
$param10 = '&'.$modbus[10].'='.$data[10].':'.$alert[10];
$param11= '&'.$modbus[11].'='.$data[11].':'.$alert[11];
$param12 = '&'.$modbus[12].'='.$data[12].':'.$alert[12];
$param13 = '&'.$modbus[13].'='.$data[13].':'.$alert[13];
$param14 = '&'.$modbus[14].'='.$data[14].':'.$alert[14];
$param15 = '&'.$modbus[15].'='.$data[15].':'.$alert[15];
$param16 = '&'.$modbus[16].'='.$data[16].':'.$alert[16];
$param17 = '&'.$modbus[17].'='.$data[17].':'.$alert[17];
$param18 = '&'.$modbus[18].'='.$data[18].':'.$alert[18];
$sent = $param0.$param1.$param3.$param4.$param5.$param6.$param7.$param8.$param9.$param10.$param11.$param12.$param13.$param13.$param14.$param15.$param16.$param17;
return $sent;
}
my controller just like this
class Send extend CI_Controller{
function data ()
{
$this->load->model('send_model');
$send = $this->model->send_model->hello();
echo $sent;
}
}
i have a problem,if tbl1 add data then i have to write adding code to my script
can anyone help me to simplify this code?
It is because you're hard-coding to send only 19 rows of data by creating 19 $param variables. In a dynamic condition, you may have an empty record-set or hundreds of records. Modify the structure of your foreach loop to the following:
$param = array();
foreach($table->result() as $row){
$param[] = '&'.$row->modbus.'='.$row->data.':'.$row->alert;
}
return $param;
Hope it answers your question.

This query show me with this active record

I am having trouble getting two tables and passing them to controller:
IN A MODEL:
function get_all_entries() {
$query = $this->db->get('entry');
return $query->result();
$this->db->select('entry_id , count(comment_id) as total_comment');
$this->db->group_by('entry_id');
$comment = $this->db->get('comment');
return $comment->result();
}
IN A CONTROLLER:
$data['query'] = $this->blog_model->get_all_entries();
$this->load->view('blog/index',$data);
How do I return $query and $comment variables to controller? I think I am doing it wrong.
Use this because you are not allowed to return twice in the same method
function get_all_entries()
{
$query = $this->db->get('entry');
$data[] = $query->result();
$this->db->select('entry_id , count(comment_id) as total_comment');
$this->db->group_by('entry_id');
$comment = $this->db->get('comment');
$data[] = $comment->result();
return $data;
}
EDITS:
In controller
function index(){
$this->load->model('mymodel');
$result = $this->mymodel->get_all_entries();
$entries = $result[0] ;
$comments = $result[1] ;
$data['entries'] = $entries;
$data['comments '] = $comments;
}
Your issue is that you're returning $query->result() in first place, return function halts the current function, so the next steps are not being processed.
Best way would be to create two methods for either $query get and $comment get.
An alternative to your issue would be
function get_all_entries() {
$query = $this->db->get('entry');
$this->db->select('entry_id , count(comment_id) as total_comment');
$this->db->group_by('entry_id');
$comment = $this->db->get('comment');
return array($query->result(),$comment->result());
}
Then in your controller
list($data['query'],$data['comment']) = $this->blog_model->get_all_entries();
$this->load->view('blog/index',$data);

Categories