explode using foreach inside codeigniter model not working - php

I have a code which separate , from the string using explode.
Now the problem is the foreach loop only iterating once. Am using this code in codeigniter model.
My code is,
//Model
$product_id = '1,2,3';
$products = explode(',', $product_id);
foreach($products as $products_id) {
echo $products_id.'<br><br>'; //output: 1
$query = $this->db->query('SELECT * FROM tbl_products WHERE products_id = "'.$products_id.'" AND products_status = "1"');
$count = $query->num_rows();
if($count > 0) {
return $result = $query->result_array();
}
else {
return 0;
}
}
The output for the above code is 1.
The other digit 2 and 3 is missing. Am I doing anything wrong. Please help me out. I can't figure it out.

To correct it, you could do this
$product_id = '1,2,3';
$products = explode(',', $product_id);
$data = [];
foreach($products as $products_id) {
echo $products_id.'<br><br>'; //output: 1
$query = $this->db->query('SELECT * FROM tbl_products WHERE products_id = "'.$products_id.'" AND products_status = "1"');
$count = $query->num_rows();
if($count > 0) {
$data = array_merge($data, $query->result_array());
}
}
if(empty($data)){
return 0;
}
return $data;
Which avoids exiting in the original if statement you return on more then 0 results or 0 results, so basically on the first iteration of the loop.
But, that said, possibly a better way to fix it is this
$product_id = '1,2,3';
$query = $this->db->query('SELECT * FROM tbl_products WHERE products_id IN( ? ) AND products_status = "1"',$product_id);
$count = $query->num_rows();
if($count > 0) {
return $query->result_array();
}else{
return 0;
}
Using IN you can avoid the foreach,explode and additional query calls, also you should use prepared queries. This should work with numbers, but strings still need to be wrapped in quotes, 'IN( "string","string", "string" )' or $string = '"string","string","string"'; as the input, which may complicate things for prepared queries.

Everthing is fine in your code .If you want get all data , Then you should return all in array . check the code :
$product_id = '1,2,3';
$products = explode(',', $product_id);
$data = array();
foreach($products as $products_id) {
echo $products_id.'<br><br>'; //output: 1
$query = $this->db->query('SELECT * FROM tbl_products WHERE products_id = "'.$products_id.'" AND products_status = "1"');
$count = $query->num_rows();
if($count > 0) {
$data[]= $query->result_array();
}
else {
$data[]= 0;
}
}
return $data;
On $data .. You can do any action with $data as like you want.

Related

Is there a way I can sort this array

I want to sort a returned value from a while loop here is my code
public function Getter($stream){
$sql1 = "SELECT reg_no FROM hs_registration ";
$sql1.= "JOIN hs_students USING(reg_no) WHERE class_id = 2";
$result1 = $database->query($sql1);
$num1 = $database->num_rows($result1);
if($num1 > 0){
$records = array();
$number_of_sub = getNoSub();
while($row = mysqli_fetch_array($result1)){
//return individual score
$total = $this->totalScoreSpreadSheet($row['reg_no'], $stream);
$flyAvg = $total / $number_of_sub;
$records[] = number_format($flyAvg,2).' '.$row['reg_no'];
}
}
return $records;
}
$averages = Getter($stream);
foreach ($averages as $avg){
echo $avg
}
Please, I want to sort the output based on the avg with the students reg_no appended to it
Output
54.20 FMS34
91.00 FMS51
72.16 FMS64
44.81 FMS23
68.52 FMS30
48.65 FMS37
My desired output is
Output
91.00 FMS51
72.16 FMS64
68.52 FMS30
54.20 FMS34
48.65 FMS37
44.81 FMS23
If your leading numbers are always two digits, then a decimal point, the two digits, then rsort($records); would suffice.
If they might be anything else, then keep a separate sorting array, then use array_multisort() to modify the $records.
public function Getter($stream): array
{
$sql = "SELECT reg_no
FROM hs_registration
JOIN hs_students USING(reg_no)
WHERE class_id = 2";
$flyAvgs = [];
$records = [];
$number_of_sub = getNoSub();
foreach ($database->query($sql) as $row) {
$total = $this->totalScoreSpreadSheet($row['reg_no'], $stream);
$flyAvg = $total / $number_of_sub;
$flyAvgs[] = $flyAvg;
$records[] = number_format($flyAvg, 2) . ' ' . $row['reg_no'];
}
array_multisort($flyAvgs, SORT_DESC, $records);
return $records;
}

How to pass multiple array of Id in where condition codeigniter?

I want to pass multiple id in where condition how to do it?
A query fetches org_id from database.
now I want to pass that in my where condition, so how to do it?
I tried foreach loop:
Below is my code:
$devices = $this->activation_m->get_activated_devices();
$org_id = array(); // create org_id array
foreach ($devices as $row)
{
$org_id[]= $row['org_id']; // assign ids into array
//$companys =$this->data['devices'] = $this->activation_m->get_company($org_id); // don't call again and again
}
//Now $org_id is array
$companys =$this->data['devices'] = $this->activation_m->get_company($org_id);
echo $this->db->last_query();
Model Code
public function get_activated_devices()
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.site_key = activation.site_key');
$this->db->from('activation');
$query =$this->db->get();
$result = $query->result_array();
return $result;
}
public function get_company($org_id)
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
$this->db->where('company.id IN',(implode(',',$org_id))); // see the change here
$this->db->from('company');
$query =$this->db->get();
$result = $query->result_array();
return $result;
}
now currently my query passes only one org_id , I want to pass all the org_id I get from my first query.
You can use where_in from active-records codeigniter
as
$devices = $this->activation_m->get_activated_devices();
$org_id = array();
foreach ($devices as $row)
{
$org_id[] = $row['org_id'];
}
$companys =$this->data['devices'] = $this->activation_m->get_company($org_id);
if( $companys->num_rows() > 0 )
{
echo "<pre>";
print_r( $companys->result());
echo "</pre>";
}
And for Model
public function get_company($org_ids = array())
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
$this->db->where_in('company.id', $org_ids ); //this is condition
$this->db->from('company');
return $this->db->get();
}
You can use codeigniter's $this->db->or_where() for the purpose. Just traverse the array of organization id's and apply or_where conditions.
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
foreach($org_id as $org)
{ // where $org is the instance of one object of active record
$this->db->or_where('company.id',$org);
}
$this->db->from('company');
$query =$this->db->get();
$result = $query->result_array();
return $result;
Another way to do this is to make a custom query by traversing the array like this and appending where clauses in string.

how to handle php forloop returning no results

Im running a for loop to gather data from a forum table, but im not quite sure what to do to make it handle if there are no results returned. Here is the code i have to gather the data.
$q = $this->db->query("SELECT * FROM newslist ORDER BY pubdate DESC");
if ($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
}
return $data; else {
return echo = "nose";
}
$q = $this->db->query("SELECT * FROM newslist ORDER BY pubdate DESC");
$data = array(); // Initialize the array in case there are no records.
if ($q->num_rows() > 0){
foreach ($q->result() as $row){
$data[] = $row;
}
}
if (empty($data)) { // If there are no records, $data will be empty.
return "nose";
}
else { // If $data has records, will return data from SQL.
return $data;
}
Explanation:
1) Initialize the $data variable. If we do not get any records, $data will not be appended, causing initialized variable $data return error. By initializing it before loop, we are overcoming it.
2) Check empty() ness of $data, if its empty, return error string, else $data.
Little bit of a flow issue. See revised solution.
$q = $this->db->query("SELECT * FROM newslist ORDER BY pubdate DESC");
if($q->num_rows() > 0){
foreach($q->result() as $row){
$data[] = $row;
}
return $data;
} //<-- this was on the wrong line
else {
return "No data!";
}
Return your data inside if condition and don't use return and echo at same time.
$q = $this->db->query("SELECT * FROM newslist ORDER BY pubdate DESC");
if ($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;// return data inside if condition
}
else {
return "nose";// remove echo from here
}
Simply You can use this
$query = $this->db->query("SELECT * FROM newslist ORDER BY pubdate DESC");
$result = $query->result_array();
$count = count($result);// counting data
if(empty($count))
{
$log = 'nose';
return $log;
}
else
{
return $result;
}

Can i get a part of an variable?

Is it possible to get an part of a variable and run this to a where loop.
function rapport_detail_kosten($idKlant){
$this->db->from('Project');
$this->db->join('Kosten', 'Kosten.idProject = Project.idProject');
if ($idKlant > 0){
$this->db->where('idKlant', $idKlant);}
$query = $this->db->get();
$project = array();
foreach($query->result() as $row){
$project[] = $row->idProject;
}
$hoi = implode(",", $project);
print_r($hoi);
$this->db->select_sum('Prijs');
$this->db->from('Kosten');
$this->db->where('Kosten.idProject',$hoi);
$query = $this->db->get();
if($query->num_rows()>0){
return $query->result();
}
else{
return false;
}
}
the $hoi has the value: 14,79,9,85,85,85,85,91,6
these are all id's but i would like to run this where statement only when the id is in this variable. So i would like to run id=6 but for example not id=7
You can use method where_in of codeigniter that search a value inside an array, in this case you can use directly $project, you don't need $hoi
try this:
$sum = 0;
$this->db->select_sum('Prijs');
$this->db->from('Kosten');
$this->db->where_in('Kosten.idProject',$project);
$query = $this->db->get();
foreach ($query->result() as $row){
$sum = $row->Prijs;
}
return($sum);
MANUAL

Only showing last item in array

I'm trying to figure out why its only showing the last child_links in the roster, events, and social objects. I've included the site that has the print_r of the array function. Any help would be appreciated.
http://kansasoutlawwrestling.com/
function getSubMenuPages()
{
$this->db->select('id');
$this->db->where('short_name', 'mainnav');
$query = $this->db->get('site_menu_structures');
$menu_id = $query->row()->id;
$this->db->select('id, short_name, is_category');
$this->db->where('menu_structure_id', $menu_id);
$query = $this->db->get('site_menu_structures_links');
if ($query->num_rows() > 0)
{
$linksArray = $query->result();
echo "<pre>";
print_r( $linksArray );
echo "</pre>";
foreach ($linksArray as $key => $link)
{
if ($link->is_category == 'Yes')
{
$this->db->select('link_name, site_content_pages_id, link_url');
$this->db->where('site_menu_structures_links_id', $link->id);
$query = $this->db->get('site_menu_structures_links_children');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$site_content_page_id = $row->site_content_pages_id;
$linksArray[$key]->child_links = array();
if ($site_content_page_id != 0)
{
$this->db->select('content_page_name, permalink');
$this->db->where('id', $site_content_page_id);
$query = $this->db->get('site_content_pages');
if ($query->num_rows() > 0)
{
$row = $query->row();
$linksArray[$key]->child_links = array(
'link_name' => $row->content_page_name,
'link_url' => $row->permalink
);
}
}
else
{
$linksArray[$key]->child_links = array(
'link_name' => $row->link_name,
'link_url' => $row->link_url
);
}
}
}
}
}
}
return $linksArray;
}
When you loop here:
foreach ($query->result() as $row)
{
$site_content_page_id = $row->site_content_pages_id;
$linksArray[$key]->child_links = array();
if ($site_content_page_id != 0)
{
you're inside another loop, so at each passage of this loop here the $key remains the same.
So, 1st external loop, ex. $key = 'key1'; I'll use some pseudo code to give the idea:
foreach results as row:
(loop nr 1):
linksarray['key1'] = empty array.
linksarray['key1'] = value;
(loop nr 2):
linksarray['key1'] = empty array
linksarray['key1'] = value2
endforeach;
2nd external loop, $Key = 'key2'
foreach results as row:
(loop nr 1):
linksarray['key2'] = empty array.
linksarray['key2'] = value;
(loop nr 2):
linksarray['key2'] = empty array
linksarray['key2'] = value2
endforeach;
I might have mis-looked something in all those loops, it's evening here and I'm a bit tired :)
Oh, and a piece of advice: your code gets easily a bit difficult to read; a small improvement would be to omit the table name (as it's not necessary), especially when it's so long; moreover, in AR you can omit the "from" clause and also chain method.
So, for ex., this:
$this->db->select('site_menu_structures_links_children.link_name, site_menu_structures_links_children.site_content_pages_id, site_menu_structures_links_children.link_url');
$this->db->from('site_menu_structures_links_children');
$this->db->where('site_menu_structures_links_children.site_menu_structures_links_id', $link->id);
$query = $this->db->get();
Could be easily rewritten as:
$query = $this->db->select('link_name,site_content_pages_id,link_url')
->where('site_menu_structures_links_id',$link->id)
->get('site_menu_structures_links_children');
Doing this might help you in identifying out the general code flow, spotting out the various runs
UPDATE
Try this
function getSubMenuPages()
{
$this->db->select('id');
$this->db->where('short_name', 'mainnav');
$query = $this->db->get('site_menu_structures');
$menu_id = $query->row()->id;
$this->db->select('id, short_name, is_category');
$this->db->where('menu_structure_id', $menu_id);
$query2 = $this->db->get('site_menu_structures_links');
if ($query2->num_rows() > 0)
{
$linksArray = $query2->result();
echo "<pre>";
print_r( $linksArray );
echo "</pre>";
foreach ($linksArray as $key => $link)
{
if ($link->is_category == 'Yes')
{
$this->db->select('link_name, site_content_pages_id, link_url');
$this->db->where('site_menu_structures_links_id', $link->id);
$query3 = $this->db->get('site_menu_structures_links_children');
if ($query3->num_rows() > 0)
{
$linksArray[$key]->child_links = array();
foreach ($query3->result() as $row)
{
$site_content_page_id = $row->site_content_pages_id;
//$linksArray[$key]->child_links = array();
if ($site_content_page_id != 0)
{
$this->db->select('content_page_name, permalink');
$this->db->where('id', $site_content_page_id);
$query4 = $this->db->get('site_content_pages');
if ($query4->num_rows() > 0)
{
$row = $query4->row();
$linksArray[$key]->child_links[]['link_name'] = $row->content_page_name;
$linksArray[$key]->child_links[]['link_url'] = $row->permalink;
}
}
else
{
$linksArray[$key]->child_links[]['link_name'] = $row->link_name;
$linksArray[$key]->child_links[]['link_url'] = $row->link_url;
}
}
}
}
}
}
return $linksArray;
}
basically, I moved the property assigment $linksArray[$key]->child_links = array(); outside the loop. Being followed by another loop, which can possibly have more values, I've created an index for each loop:
$linksArray[$key]->child_links[]['link_name'] = $row->content_page_name;
$linksArray[$key]->child_links[]['link_url'] = $row->permalink;
Try replacing this block of code:
$this->db->select('link_name, site_content_pages_id, link_url');
$this->db->where('site_menu_structures_links_id', $link->id);
$query = $this->db->get('site_menu_structures_links_children');
if ($query->num_rows() > 0)
{
$linksArray[$key]->child_links = array();
foreach ($query->result() as $row)
{
$site_content_page_id = $row->site_content_pages_id;
if ($site_content_page_id != 0)
{
$this->db->select('content_page_name, permalink');
$this->db->where('id', $site_content_page_id);
$query2 = $this->db->get('site_content_pages');
if ($query2->num_rows() > 0)
{
$row2 = $query2->row();
array_push($linksArray[$key]->child_links, array(
'link_name' => $row2->content_page_name,
'link_url' => $row2->permalink
));
}
}
else
{
array_push($linksArray[$key]->child_links, array(
'link_name' => $row->link_name,
'link_url' => $row->link_url
));
}
}
}

Categories