Optimize query for mysql and php - magento

I have table with fields like id,name and values like (1,"sony,nokia,htc"),(2,"sony")(3,"Samsung").I fetch the records but my logic goes longer than my expection.I want to exlode name if it contains "," and fetch unique records.My result will look like
Name array will be { 0 =>"sony",1=>"HTC",2=>"Nokia"}.My dummy logic is here (This is incomplete not working properly.)
<?php
$row = array("sony,htc,nokia","htc","sony");
foreach ($row as $key => $valuek) {
if(strpos($valuek['value'], ",") !== false)
{
$str[] = explode(",",$valuek['value'] )
?>
<option value="<?php echo $valuek['value']?>"><?php echo $valuek['value']?></option>
<?php
}
?>
<option value="<?php echo $valuek['value']?>"><?php echo $valuek['value']?></option>
<?php } $i++;}?>

You don`t need to do explode that
At the start where you get all your data and stored in array you can just used array_unique()
$row = array("sony,htc,nokia","htc","sony"); // all fetch data from db.
$row = implode(',',$row); // first convert the array -> strings
$row = explode(',',$row); // then return back to array and you can now use array_unique
$row = array_unique($row); // this will filter all data with uniqueness and drop some data that have same value
then you can use this to loop the data on.
for($i=0;$i<count($row)){
echo '<option value="'.$row[$i].'">'.$row[$i].'</option>';
}
this will make your code shorter and easy to manage..

Related

how can I get all data in one column?

this is the actual I want to expectI want to get all the fees in one column, I have 5 fees but only one fee are appending
foreach ($client_class->getLoanFeesInfoById($li_id) as $row_d){
$fee_id = $row_d->fee_id;
foreach ($fees_class->getInfoByFeeId($fee_id) as $row_e)
{
$fee_name = $row_e->fee_name;
$default_amount = $row_e->manual_default_amount;
$disbursement_amount = $loan_amount - $default_amount;
}
}
echo "<tr>
<td>".number_format($default_amount)."-".$fee_name."</td>
<td>".$deposit_code."</td>
<td>P".number_format($disbursement_amount)."</td>
</tr>";
When you echo <td>".number_format($default_amount)."-".$fee_name."</td>, you will only get the last values that have been obtained in the foreach. So as a solution you can use a variable inside the inner foreach to store all the fee.
$fee = '';
foreach ($fees_class->getInfoByFeeId($fee_id) as $row_e)
{
$fee_name = $row_e->fee_name;
$default_amount = $row_e->manual_default_amount;
$disbursement_amount = $loan_amount - $default_amount;
$fee .= number_format($default_amount)."-".$fee_name."<br/>";
}
Then you can echo as
<td>".$fee."</td>

Iterating through result set in Laravel controller

I am trying to simply iterate though a result set in laravel on the controller side. This is what I tried but I get the following error:
Cannot use object of type stdClass as array
Controller snippet:
$result = DB::select($query);
foreach($result as $r){
echo $r['email'];
}
I appreciate any help with this,
Thanks in advance!
You need to use it as an object:
$result = DB::select($query);
foreach($result as $r){
echo $r->email;
}
Or if for some reason you want to use it as array, you need to convert it first:
$result = DB::select($query)->toArray();
foreach($result as $r){
echo $r['email'];
}
After pulling data from database you can convert it to array but it is optional, it's depends on your necessity then you can simply use the foreach to loop through to each distinct object and get access their property
$data = DB:: table('categories')
->where('parent_id', $request->value)
->get()->toArray();
$output = '<option value="">Select '.ucfirst($request->dependent).'</option>';
foreach($data as $row){
$output.= '<option value="'.$row->id.'">'.$row->title.'</option>';
}
return response($output, 200);
The Laravel Collection class supports the standard methods for iterables: map, sort, filter etc. see: vendor/laravel/framework/src/Illuminate/Collections/Collection.php
if you're querying on a model:
$results = MyAwesomeModel::where('something' '=' 'other')->get();
//this is valid
$results->map(function($result) {
echo $result->field;
});
//this is also valid
for($i = 0; $i < sizeof($results); $i++){
echo $results[$i]->field;
}
I would suggest avoiding ->toArray() on hydrated results (instances of models) because you loose all the model properties.

codeigniter form_dropdown return wrong value

My Model,
function get_partners_name()
{
$q = $this->db->select("id,fname,lname")
->from('partner');
$all_partners = $q->get()->result();
$data = array();
foreach($all_partners as $partner)
{
$data[$partner->id] = $partner->fname.' '.$partner->lname;
}
return $data;
}
my controller var_dump($partners) data is,
array (size=2)
38 => string 'Mahesh' (length=6)
40 => string 'Rahul' (length=4)
My view,
<?php array_unshift($partners, "-Select-");?>
<?php echo form_dropdown('parnter', $partners,'',''); ?>
so in dropdown i want to display,
<option value='0'>-Select-</option>
<option value='38'>Mahesh</option>
<option value='40'>Rahul</option>
But it display,
<option value='0'>-Select-</option>
<option value='1'>Mahesh</option>
<option value='2'>Rahul</option>
from the PHP manual.
'array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.'
so your keys are being renumbered when using unshift.
since the select option should never be selected I would suggest hardcoding it into the view. also don't give it a value if you don't want users to select it.
<select name='foo'>
<option disabled>-Select-</option>
<?php
foreach($partners as $partner){
echo '<option value="';
echo $partner->id;
echo '">';
echo $partner->name;
echo '</option>';
}
?>
</select>

repopulating the select list generated from database in codeigniter

Hi. I have the form in which I use form_validation If the user make any mistake (leave some required fields empty), user is redirected back to the form, and the form has been re-populated. All works, except my select , which is generated from the database.
Here is my code from the view:
echo "<select name='parentid'" . set_value("parentid"). ">";
echo '<option value = "0">None</option>';
foreach ($faq_categories as $row => $option) {
echo "<option value=" . $option['catid'] . ">" . $option['categoryname']. "</option>";
}
echo '</select>';
Here is my controller code:
public function displayAddFaqCategoryForm($error = null)
{
$data['title'] = "Add new FAQ Category";
$data['main_content'] = 'addFaqCategory';
$selectWhat = array('tname' => 'faq_categories',
'sortby'=> 'catid',
'how' => 'asc'
);
$this->load->model('selectRecords');
$data['faq_categories'] = $this->selectRecords->selectAllRecords($selectWhat);
$this->load->vars($data);
$this->load->view('backOffice/template');
} // end of function displayAddFaqCategoryForm
And here is the model code:
public function selectAllRecords($selectWhat = array())
{
$data = array();
$tname = $selectWhat['tname'];
$sortby = $selectWhat['sortby'];
$how = $selectWhat['how'];
$this->db->order_by($sortby,$how);
$query = $this->db->get($tname);
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
} // end of function selectAllRecords
I am not getting any error messages, just the select is not repopulated with last used. Any help will be deeply appreciated.
You're using set_value() incorrectly
echo "<select name='parentid'" . set_value("parentid"). ">";
It's meant to output the actual value (for text inputs). This would produce something like:
<select name='parentid'ActualValue>
Which is not how a <select> element is populated, and is invalid HTML. See the correct usage in the Form Helper docs.
You can use set_select(), and it goes on your <option>:
foreach ($faq_categories as $row => $option) {
echo "<option value=".form_prep($option['catid']).'"';
echo set_select('parentid', $option['catid']); // outputs selected="selected"
echo ">".html_escape($option['categoryname'])."</option>";
}
I've taken a few other liberties with your code here as you can see, to be on the safe side (always).
If this is too much of a mess, you might be interested in the form_dropdown() function.

in one foreach call second foreach! codeigniter

hier is the problem:
in codeigniter in controller I have next code:
$query_not_voted = "SELECT * FROM photos WHERE p_id NOT IN (SELECT distinct p_id FROM p_votes where u_id = ".$this->session->userdata('u_id').") LIMIT ".$this->db->escape_str($segment_url).", ".$config['per_page'];
$q = $this->db->query($query_not_voted);
$data['myphotos'] = $q->result_array();
foreach($data['myphotos'] as $key=>$val)
{
$query_g = "SELECT * FROM users WHERE u_id = (SELECT u_id FROM p_votes WHERE p_id = ".$val['p_id'].")";
$q_2 = $this->db->query($query_g);
$data['allvotess'] = $q_2->result_array();
$query_u = "SELECT * FROM users WHERE u_id = ".$val['u_id']." LIMIT 0, 5";
$q_1 = $this->db->query($query_u);
$data['author'] = $q_1->result_array();
}
So now I have $data['myphotos'] and this is can be outputted in view with next codes:
<?php foreach ($myphotos as $keys => $myphoto){ ?>
<div id="voteblock">
<div id="voteleft">
<img src="<?php echo base_url().$myphoto['p_thumb']; ?>" />
</div>
<?php } ?>
but how can I output $data['allvotess'] in last foreach loop?
I tried to do same, but didn't work out.
Then I tried to push the results inside $data['myphotos'] and no good result!
So What I'm Doing???
Just need someone to help me with foreachloop insite foreachloop!!!
For a week I just can't do, I can even pay for solution right now!!!
I posted also at codeingiter forum, but they say it's easy hier is link
Generally in views I use the more semantic way to write foreach and if statements, and I'll also illustrate a tiered foreach loop...
$array1 = array(1,2,3,4);
$array2 = array(1,2,3,4);
$array3 = array(1,2,3,4);
$second_array[] = $array1;
$second_array[] = $array2;
$second_array[] = $array3;
so now we have $second_array that is a multi-dimensional array...
$data->second_array = $second_array;
$this->load->view('your/view',$data);
in a view file...
<? foreach($second_array as $array): ?> //<--start first foreach loop
<div>do some stuff</div>
<? foreach($array as $array_item): ?> //<--start second foreach loop, inside the first
<div>do some other stuff for every item in $array</div>
<? endforeach; ?> //<--end first foreach
<? endforeach; ?> //<--end second foreach

Resources