Jump to content

suppress foreach error warnings


ashutoash

Recommended Posts

I use PHP's PDO extensively for data grabbing and inserting. When I am selecting data, the return is a PHP PDO object which in itself contains select statements. So I use foreach to parse through the object and build a table. For cells which I have data it's fine but for cells which do not get any data meaning that have no entry in the db, php throws out a error PHP Warning:  Invalid argument supplied for foreach().

I tried using if(is_array) and also @ to suppress them but no luck :'( :'( :'(. Can anyone point me to the right direction for suppressing these errors/warnings!!

Link to comment
Share on other sites

do you need a code snippet...here is some:

 

$getSite = "SELECT * FROM orderTable WHERE siteName = 'Atlanta' ORDER BY siteName";
$getSiteResults = $getData->db->getLocalQuery($getSite);
foreach($getSiteResults as $site)
{
                 $result = $site["placeName"];
        }

 

I am getting data...that's fine but at some instances it throws the warning PHP Warning:  Invalid argument supplied for foreach(). I read online that using @ will suppress these errors...but for me it does not.

Link to comment
Share on other sites

Suppression is BAD! Avoid doing it at all costs.

 

Instead, look into proper checks

 

<?php 

$var = array(
'key1' => 'val1',
'key2' => 'val2',
'key3' => 'val3',
);

if( is_array($var) || is_object($var) )
foreach( $var as $key => $value ) {
	echo $key. '=>' .$value. '<br>';
}
else echo 'Can not loop<br>';

/////////////////////////////////////////////////

class obj {
public $prop1 = 'val1', $prop2 = 'val2', $prop3 = 'val3';
private $prop4 = 'wontbeshown';
}
$var = new obj();

if( is_array($var) || is_object($var) )
foreach( $var as $key => $value ) {
	echo $key. '=>' .$value. '<br>';
}
else echo 'Can not loop<br>';

/////////////////////////////////////////////////

$var = FALSE;

if( is_array($var) || is_object($var) )
foreach( $var as $key => $value ) {
	echo $key. '=>' .$value. '<br>';
}
else echo 'Can not loop<br>';

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.