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.
Related
As I try to consolidate my code and make it more available to other projects, I've run into a problem:
variables that were generated and available are not anymore when that routine is moved to a function:
This is the query:
$count = "SELECT eid, Count, Name, name2, Email, pay FROM h2018";
THIS WORKS FINE:
$result = $mysqli->query($count);
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
echo($a." and ".$value."<BR>");
}
NOT WORKING FINE:
function avar($result) {
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
}
}
$result = $mysqli->query($count);
avar($result);
echo($a." and ".$value."<BR>");
I thought the variable variables would be available from outside of the function. I tried doing a return, but that didn't help. I also tried to global $$key, but that didn't work either.
What am I doing wrong?
There is multiple mistakes or missing steps like return or array
function avar($result) {
$data=array();
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$data[$key] = $value;//if there is multiple records then used array otherwise you should used variable
}
return $data;
}
$result = $mysqli->query($count);
$data=avar($result);//get return value
print_r($data);
Please, read the PHP documentation about the Variable Scope for more information. The variables inside your function are local so you cannot access them outside of your function. You would have to return something.
For example, this could work:
function avar($result) {
$resultArray = false;
$row = $result->fetch_assoc();
foreach ($row as $key => $value) {
$resultArray = [
'key' => $key,
'value' => $value
];
}
return $resultArray;
}
$result = $mysqli->query($count);
$queryResult = avar($result);
if ($queryResult) {
echo 'Key: ' . $queryResult['key'] . ' | Value: ' . $queryResult['value'];
}
Please do note that fetch_assoc will return an array with multiple items if there is more than one result. In my example only one (and the last) result will be returned.
Edit: As #Nigel Ren said in his comment. In this case you're basically rebuilding an array which is going to look (nearly) the same as the array which is being returned by fetch_assoc, which is pointless. My function can be used if you want to add conditions in the future, or manipulate some data. Otherwise, don't use a function and just use the results from fetch_assoc.
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
I can't retrieve values from $info (as stated below) in CodeIgniter View.
Here is the scenario:
I explained everything the code.
function info() {
{...} //I retrieve results from database after sending $uid to model.
$dbresults = $this->my_model->get_info($uid); //Assume that this model returns some value.
foreach($dbresults as $row) {
$info = $row->address; //This is what I need to produce the results
$results = $this->my_model->show_info($info);
return $results; //This is my final result which can't be achieved without using $row->address. so first I have to call this in my controller.
}
// Now I want to pass it to a view
$data['info'] = $results;
$this->load->view('my_view', $data);
//In my_view, $info contains many values inherited from $results which I need to call one by one by using foreach. But I can't use $info with foreach because it is an Invalid Parameter as it says in an error.
using $result inside foreach is not reasonable. Because in each loop $result will take a new value. So, preferably use it as an array and then pass it to your view. Besides, you should not use return inside foreach.
function info() {
{...} //I retrieve results from database after sending $uid to model.
$dbresults = $this->my_model->get_info($uid); //Assume that this model returns some value
$result = array();
foreach($dbresults as $row) {
$info = $row->address; //This is what I need to produce the results
$result[] = $this->my_model->show_info($info);
}
// Now I want to pass it to a view
$data['info'] = $result;
$this->load->view('my_view', $data);
}
to check what $result array has do var_export($result); or var_dump($result); after the end of foreach. and make sure that this is what you want to send to your view.
Now, in your view you can do:
<?php foreach ($info as $something):?>
//process
<?php endforeach;?>
Please remove return statement from
foreach($dbresults as $row) {
$info = $row->address; //This is what I need to produce the results
$results[] = $this->my_model->show_info($info);
// return $results; remove this line from here;
}
$data['info'] = $results; // now in view access by $info in foreach
$this->load->view('my_view', $data);
now $info can be access in view.
hope this will help you!
I have multidimensional array which is a query returning the info from a table named 'users'. In another part of my code I need to get the records of only one certain user and I want to take it using the array I mentioned above. It's of type:
This is probably what you're looking for:
$row = NULL;
foreach ($parent as $key => $child)
{
if (1 == $child['id'])
{
$row = $child; break;
}
}
if (isset($row))
{
// Stuff to do with the chosen row
}
$main = // your array
foreach ($main as $index => $sub) {
foreach ($sub as $subIndex => $item) {
if ($item['id'] == xxx) {
return $main[$index][$subIndex];
}
}
}
IMO using for loops (rather that foreach) would make it easier for you to reference the variable you need (by using the for loop variable to look up the appropriate row in the array)
HTH,
David
This is going to be my first time building an associative array. And if anyone can help me I would be grateful.
Basically, I want to loop through a directory of XML files. I want to find out if a certain editor was the editor of this file, and if the query is true, I would like to grab two pieces of information and achieve the result of an associate array with those two pieces of information for every case where the editor's name is found.
So here's what I have got so far:
function getTitleandID($editorName) {
$listofTitlesandIDs = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
if ($editorName == $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()"))
{
$title = $xmldoc->xpath("//tei:teiHeader/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id[1]");
$listofTitlesandIDs[] = //I don't know what to do here
}
else
{
$listofTitlesandIDs = null;
}
}
return $listofTitlesandIDs
}
This is about where I get stuck. I'd like to be able have $listofTitlesandIDs as an associative array where I could call up the values for two different keys, e.g. $listofTitlesandIDs['title'] and $listofTitlesandIDs[$id]
So that's about it. I'm grateful for any help you have time to provide.
Well I'm sure this is a little clumsy (the result of an amateur) but it has given me the result I want.
function getTitlesandIDs($EditorName) //gets titles and IDs for given author
{
$list = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
$title = $xmldoc->xpath("//tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id");
$editorName = $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()")
if ($editorName[0] == "$EditorName")
{
$result = array("title"=>$title[0], "id"=>$id[0]);
$list[] = $result;
}
}
return $list;
}
With this I can call the function $list = getTitlesandIDs('John Doe') and then access both the title and id in the associative array for each instance. Like so:
foreach ($list as $instance)
{
echo $instance['title'];
echo $instance['id'];
}
Maybe that will help somebody some day -- let me know if you have any advice on making this more elegant.
$listofTitlesandIDs[$id] = $title;
You should loop over the array then using the foreach loop.