Let's think that we have a db and a model function that retrieve a query result like this:
public function lista_ordini ($idcliente)
{
$this->db->select('ordini.num_fattura, misure.cosplay, ordini.data_richiesta,
ordini.anticipo, ordini.data_consegna,
ordini.saldo_totale, ordini.stato');
$this->db->join('misure', "ordini.id_cliente = $idcliente");
$query = $this->db->get('ordini');
if ($query && $query->num_rows() > 0){
return $query;
}else{
echo "errore generazione query ordini";
}
}
}//This is missing in your original, I'm not sure if it's a typo
Using codeigniter's table helper to generate a table:
<?php echo $this->table->generate($query); ?>
I can generate the table...and this is ok and works...
but, What if I want that every rows has a specific field (or the entire row if it's simpler) with href link? (this link will pass thorough GET method a variable for generate another query, but I don't figure out yet how that will work, this is just an hobby project)
I try this:
public function lista_ordini ($idcliente)
{
$this->db->select('ordini.num_fattura, misure.cosplay, ordini.data_richiesta,
ordini.anticipo, ordini.data_consegna, ordini.saldo_totale,
ordini.stato');
$this->db->join('misure', "ordini.id_cliente = $idcliente");
$query = $this->db->get('ordini');
if ($query && $query->num_rows() > 0) {
$rows = $query->row();
foreach ($rows as &$row) {
$row['num_fattura'] = ''.$row['num_fattura'].'';
}
return $rows;
}else{
echo "errore generazione query ordini";
}
}
I'm pretty sure that foreach loop is the way, but I can't understand how, cause I have so much errors that I cannot understand...to make this simply, my code doesn't work, and I think that I need some semantic advice.
thank you in advace
There is a logical problem in the foreach loop here:
foreach ($rows as &$row) {
$row['num_fattura'] = ''.$row['num_fattura'].'';
}
return $rows;
Each time the loop runs you are changing the value of $row, but when it completes you are returning $rows, which is unchanged.
Instead, you could edit the original array, using $k => $v to access the key and value inside the foreach loop:
foreach ($rows as $k => $v) {
$rows[$k]['num_fattura'] = ''.$rows[$k]['num_fattura'].'';
}
return $rows;
I know what you're trying to do, but I dont understand how you are trying to do it. Here's How I would do it:
//controller method
public function show_data()
{
$this->load->library('table');
$data['table_data'] = $this->some_model->get_the_data();
$this->load->view('some_view_that_will_contain_my_table', $data);
}
Now in my view, I'd generate the table:
<!doctype html>
...
<?if(!empty($table_data)):?>
<? $this->table->set_heading('column_1', 'column_2');?>
<?foreach($able_data as $table_row):
$this->table->add_row(
array('data'=>''.$table_row['column_1'].'.'),
array('data'=>''.$table_row['column_2'].'.'),
);
endforeach;?>
<?= $this->table->generate();?>
<?endif;?> //or display an empty table
Related
Need to bind Page drop-down conditionally on base of 'Content' table. Page titles are stored in an associative array and 'Content' table have page code stored in it. Here is the code
Function which return page titles
public function getPageTitles(){
$pageTitles = array("Home"=> "Home",
"AboutUs"=> "About Us", //AboutUs will save in database as pageCode
"Features"=> "Features",
"ContactUs"=> "Contact Us");
return $pageTitles;
}
Function which checks if page have content or not:
public function getPageTitlesWithNoContent()
{
$pageTitles = $this->getPageTitles();
$this->db->distinct('pageCode');
$this->db->select('pageCode');
$this->db->from('content');
$this->db->where('status', 1);
$data = $this->db->get();
$queryResult = $data ? $data->result_array() : 0 ;
$emptyPageTitle = array();
foreach($pageTitles as $x => $x_value)
{
$hasContent = in_array($x, $queryResult);
if (!$hasContent){
$emptyPageTitle[$x] = $x_value;
}
}
return $emptyPageTitle;
}
This function is returning all page titles.. new to php no idea what is wrong
Check name fields in table is same? With Uppercase first char?
Also change your code in this loop:
foreach($pageTitles as $x => $x_value)
{
if (in_array($x, $queryResult)){
$emptyPageTitle[$x] = $x_value;
}
}
I remove ! negative in check condition
#NMathur I think you almost got it. Made some changes for you in that code, Check it.
public function getPageTitlesWithNoContent() {
$pageTitles = $this->getPageTitles();
$this->db->select('pageCode');
$this->db->from('content');
$this->db->where('status', 1);
$this->db->group_by('pageCode');
$query = $this->db->get();
$queryResult = array();
foreach ($query->result_array() as $row) { // This loop should need to form an array based on query result
$queryResult[$row['pageCode']] = $row['pageCode'];
}
$emptyPageTitle = array_diff_key($pageTitles,$queryResult); // Compares the keys from array1 against the keys from array2 and returns the difference
return $emptyPageTitle;
}
As #TamilvananN guided, I printed the queryResult and tried this workaround:
foreach($pageTitles as $x => $x_value)
{
foreach ($queryResult as $item)
{
if (!($x == $item['pageCode'])){
$emptyPageTitle[$x] = $x_value;
}
}
}
It is working, but as you can see this has loop in a loop .. that can be very costly .. can you please share any fast way to compare the results.
I am trying to add multiple language options with the database. I created a table as follows.
And my PHP function is:
public function Languages(){
$query=mysqli_query($this->db,"
SELECT * FROM languages") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
}
So also I used the following code for showing result but I am getting the empty result:
<?php
$language = $ReSult->Languages();
$userLanguage = 'english';
echo $language['your_family'][$userLangauge];
?>
I know if I use $language['1'][$userLanguage]; then I get a result but I don't want to use id's here. Is there any way to do that to show results without using ids?
You could store the results in an associative array:
while ($row = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$data[$row['lang_key']] = $row;
}
This way, you can access the data directly by its key:
echo $language['your_family'][$userLangauge];
checkout this
function getIndex($language , $key)
{
foreach ($language as $row)
{
if (strcmp($row["lang_key"] , $key)==0) {
return $row["id"]
}
}
return null;
}
...
echo $language[getIndex($language , "your_family")][$userLanguage];
You can try like this way,
while ($row = mysqli_fetch_assoc($query)) {
$data[$row['tagKey']] = $row;
}
This is my code as of now which returns Hassum Harrod profile as JSON which is perfect. What I need to happen is for my parameter to be passed into the query string instead of having a name so that when the url is passed a name the query returns that person's profile from the DB. When I change the name Hassum Harrod to the variable $name I get the following error:
Unknown column 'Hassum' in 'where clause'
SELECT name, short_name, reknown, bio FROM profile WHERE name = Hassum%20Harrod
This is my code as now:
Controller
public function getPerson($name) {
// loads the DBModel.php
$this->load->model('DBModel');
$query = $this->db->query("SELECT name, short_name, reknown, bio FROM profile WHERE name = 'Hassum Harrod'");
$data['profile'] = $query->row();
$this->load->view('profileView', $data);
}
View
echo json_encode($profile);
Please Read : http://www.codeigniter.com/user_guide/general/models.html
http://www.codeigniter.com/user_guide/database/query_builder.html
Try this way
Add this method to your model it should be like this
// in your model
public function getNames($name) {
$data = array();
$this->db->select(*);
$this->db->like('name', $name);
$query = $this->get('profile');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data[] = $row;
}
}
return $data;
}
Your Controller should be like this
public function getPerson($name) {
$this->load->model('DBModel');
$data = $this->DBModel->getNames($name);
// you can encode in json here
$data['profile'] = json_encode($data);
$this->load->view('profileView', $data);
}
http://www.codeigniter.com/user_guide/general/controllers.html
In view :
echo $profile;
You are using LIKE keyword in your query so we could assume there would be more than one result in return from DB. In that case you would need $query->result() instead. Secondly, even if there is just one returned row, this code:
$data['profile'] = $query->row() > 0;// assigning variable to condition (TRUE|FALSE)
will return boolean value, but not result itself.
This is simplified code for that and you can check:
<?php
$a = ['a', 'b', 'c'];
var_dump($b = $a > 0);// TRUE
Feel free to start using basic examples from docs. It will help you maintaning code:
$query = $this->db->query("YOUR QUERY");
$row = $query->row();
if (isset($row))
{
echo $row->title;
echo $row->name;
echo $row->body;
}
Again, if you expect only one possible row from DB, you can try with this code. But if you are not certain if there would be several possible rows, you have to use code for retreiving that:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
When you set this all working than you can work on converting object or array to JSON string.
It would follow syntax:
$json = json_encode($row);
If multiple rows is returned, it would be most easier to return result_array() or row_array() from DB since arrays are easily converted ti JSON, although there are suitable solutions.
After all, model that is loaded at the beginning of method is not used at all.
Docs.
I'm having trouble getting this loop to return all of the rows that I know mysql is generating in this query. The objects in my javascript console are returning as I would like them to; however, I'm only getting the last row from each unique $row->student_id. I can tell that each unique row->student_id is being overwritten by the previous, but I'm not sure how else to do this logic.
This is part of a Codeigniter model. My controller is performing a json_encode function on this function, then I'm pulling this data into my view with jQuery $.ajax wired to a handlebars.js template. I'm aware that I could use ember for data bindings, but that is beyond my expertise at this time.
$query = $this->db->get();
if ($query->num_rows() > 0) {
$prev = null;
foreach ($query->result() as $row) {
if ($prev != $row->student_id) {
$data[$row->student_id] = array(
'first' => $row->last_name,
'last' => $row->first_name);
$data[$row->student_id]['dorc'] = array($row->debit_or_credit);
$prev = $row->student_id;
} else {
$data[$row->student_id]['dorc'][] += $row->debit_or_credit;
}
}
return $data;
} else {
return array();
}`
Your second if condition is not correct. You should replace it by this :
foreach ($query->result() as $row) {
if (!isset($data[$row->student_id])) { // Creates the row if not exists
$data[$row->student_id] = array(
'first' => $row->last_name,
'last' => $row->first_name);
}
if (!isset($data[$row->student_id]['dorc'])) { // Create the dorc key if not exists
$data[$row->student_id]['dorc'] = array($row->debit_or_credit);
} else { // if it exists, push the debit_or_credit row value
$data[$row->student_id]['dorc'][] = $row->debit_or_credit;
}
}
I'm running a query and then decrypting it in the controller. After it is decrypted I was putting the results into an array and sending that to the view. The problem is with this solution I need to rewrite all of my views to parse the arrays sent instead of the active record objects sent before.
Is there a way to turn the decrypted array back into an object that will work with existing active record code in the view?
Before
Controller:
$name = $this->Clients_model->getNameData('*','client_id='.$clid,'');
$data['name'] = $name;
$this->load->view('names/name_view',$data);
View:
if($name->num_rows()) > 0){
foreach($name->result() as $row){
echo $row->data;
[...]
Now
Controller:
$name = $this->Clients_model->getNameData('*','client_id='.$clid,'');
$nameArray= array();
foreach ($name->result() as $row){
$x = $row;
$keys = array('id','client_id');
$unenc = array();
foreach ($x as $key=>$value){
if(! in_array($key, $keys)){
$unenc[$key]=$this->encrypt->decode($value,$this->e_key);
}else{
$unenc[$key]=$value;
}
}
array_push($nameArray,$unenc);
}
//Creates an object with the data, but doesn't work with CI active record
//foreach ($nameArray as $akey => $aval) {
// $namea -> {$akey} = $aval;
//}
//return $data;
$data['name'] = $nameArray;
$this->load->view('names/name_view',$data);
View:
if(count($name) > 0){
foreach($name as $key=>$row){
echo $row['data'];
[...]
In the second (now) controller there is some commented out code that will make an object, but it doesn't behave as expected with active record. Is there a way to take the $nameArray() array and change it into an object that will work with existing view code (such as the code in the 'before:view' above)?
Thanks!
I asked this question over on the CI forums and got some brilliant help from user mddd: http://codeigniter.com/forums/viewthread/157516/#760320
The solution ended up being to work on the mysql result object within the controller:
$name = $this->Clients_model->getNameData('*','client_id='.$clid,'');
$dummy = $name->result();
$ignore_keys = array('id', 'client_id');
// watch! we're getting the row as a reference so we're really changing it; not working on a copy
foreach ($name->result_object as &$row) {
foreach (get_object_vars($row) as $key=>$value){
if(!in_array($key, $ignore_keys)){
$row->$key = $this->encrypt->decode($value,$this->e_key);
}
}
}
$data['name']=$name;
$this->load->view('names/name_view',$data);
this allows me to only modify the queries in the controllers instead of the queries and all the views.