Reputation: 5815
I am getting error: Invalid argument supplied for foreach()
This is my class for connecting to database:
class dbMySql {
static function Exec($query) {
// open database
$conn = mysql_connect('localhost','root','****');
if($conn == false) {
throw new Exception(mysql_connect_error());
}
mysql_select_db('data',$conn);
$result = mysql_query($query,$conn);
if(is_bool($result) && !$result) {
$error = mysql_error($conn);
mysql_close($conn);
throw new Exception($error);
}
mysql_close($conn);
return $result;
}
}
And I have this code:
echo '{ "results" : [ ';
$gettruck_result = dbMySql::Exec("SELECT id, name, lat, lng FROM data)");
$result_array = array();
foreach($gettruck_result as $row) {
$row_object = '{';
$row_object .= '"id": "' . $row['id'] . '", ';
$row_object .= '"name": "' . $row['name'] . '", ';
$row_object .= '"lat": "' . $row['lat'] . '", ';
$row_object .= '"lng": "' . $row['lng'] . '", ';
$row_object .= '}';
$result_array[] = $row_object;
}
$result_str = implode(", ", $result_array);
echo $result_str;
echo " ] }";
?>
Any idea why am I getting error in foreach loop?
Upvotes: 2
Views: 129
Reputation: 2363
You have checked result array is empty or not..
if(mysql_num_rows($gettruck_result)>0)
{
foreach($gettruck_result as $row) {
.
.
}
}
Upvotes: 0
Reputation: 666
You have to replace:
foreach($gettruck_result as $row) {
... with ...
while($row = mysql_fetch_assoc($gettruck_result)) {
Upvotes: 3