Welcome Guest, Not a member yet? Register   Sign In
Invalid argument supplied for foreach()
#1

[eluser]atulswe1[/eluser]
1.controller

function customer_area()
{
$this->load->model('cus_model');
$data['row']=$this->cus_model->cusall();
$this->load->view('customer_view',$data);
}

2.models

function cusall()
{

$q = $this->db->get('customer');

$this->db->select('*');
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[]=$row;
}
return $data;
}

}


3.views



<table border="1" height="200" width="200" bordercolor="#003366">
<tr><th>ID</th></td><th>NAME</th><th>Type</th><th>Address</th><th>Mobile</th><th>Skype_Id</th><th>Email</th><th colspan="2">Actiom</th></tr>
&lt;?php
foreach($row as $r)

{
echo "<tr>";
echo "<td>". $r->id ."</td>";
echo "<td>". $r->name ."</td>";
echo "<td>". $r->type ."</td>";
echo "<td>". $r->address ."</td>";
echo "<td>". $r->mobile ."</td>";
echo "<td>". $r->skype_id ."</td>";
echo "<td>". $r->email ."</td>";
echo "<td>". anchor('customer/input/'.$r->id,'Edit') ."</td>";
echo "<td>". anchor('customer/del/'.$r->id,'Delete') ."</td>";
echo "</tr>";
echo "<br>";
}


?&gt;
</table>


i dont understand ..wher is tha problem...pls help me
#2

[eluser]PhilTem[/eluser]
Tha problem is probably in your
Code:
if ( $q->num_rows() > 0 )
since it will most likely not find any rows with your query (for whatever reason, but maybe also because you select() AFTER you get()).
You return something only if you have found something. If you found nothing you return NULL and cannot foreach-loop over it.

You should have something like
Code:
$return = array();

if ( $q->num_rows() > 0 )
{
  foreach ( $q->result() as $row )
  {
    $return[] = $row;
  }
}

return $return; // Will always be an array, if something found with count($return) > 0 otherwise just an empty array.

PS: It may also just not work because you're not using the code-tags Wink
#3

[eluser]atulswe1[/eluser]
philtem......im using your code but not solve my problem
#4

[eluser]CroNiX[/eluser]
Code:
function cusall()
{        
  return $this->db
    ->get('customer')
    ->result();      
}

Why people iterate over the result array just to assign it to another array I don't understand. This will return either an empty array if there aren't any results or an array of result objects if there are results.
#5

[eluser]CroNiX[/eluser]
also, db::get() should be after everything else (selects, wheres, etc), as get() is what executes the query. So the select() under the get() isn't doing anything at all except wasting processing power by setting up a new query that doesn't get used. Using get() by itself will return all results for the table.




Theme © iAndrew 2016 - Forum software by © MyBB