Jump to content

foreach error


tjverge

Recommended Posts

Hello,

 

Is there a way to make a message appear on the screen if there is an error in a foreach loop?

 

I'm using the below code, and as long as valid information is entered into the form it works perfect, but if the wrong information is entered I want it to show on the screen "Wrong info entered"

 

right now it just shows "Warning: Invalid argument supplied for foreach() in /home5/ccccomma/public_html/new/register.php on line 30" when entered wrong

 

$api = mysql_real_escape_string($_POST['fullapi']);
$api = stripslashes($api);
$userid = mysql_real_escape_string($_POST['userid']);
$userid = stripslashes($userid);
$url = 'http://api.eve-dev.com/account/Characters.xml.aspx?apiKey='.$api.'&userID='.$userid;
$xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);
foreach ($xml->result->rowset->row as $name)
{
$charid = $name['characterID'];
$charname = $name['name'];
$corpname = $name['corporationName'];

mysql_query("INSERT INTO memberpilots (id, member, cname, userid, api, cid, corpname) VALUES ('', '$username', '$charname', '$userid', '$api', '$charid', '$corpname')");
}

 

Thank you

Link to comment
https://forums.phpfreaks.com/topic/240812-foreach-error/
Share on other sites

Since foreach() requires an array, make sure $xml is_array before allowing the foreach() loop to run.

 

And BTW, you use mysql_real_escape_string() in a attempt to sanitize your incoming string data, then you immediately negate the escaping with stripslashes(), so the net result is you have exactly what you started with, an unsanitized string. stripslashes should not be used without first checking for magic_quotes_gpc, and then it should be used before escaping the data.

 

if( get_magic_quotes_gpc() ) {
     $data = stripslashes($data);
}
$data = mysql_real_escape_string($data);

Link to comment
https://forums.phpfreaks.com/topic/240812-foreach-error/#findComment-1236855
Share on other sites

Yeah, that should be just fine. I also just noticed you're running the query in a loop, which should be avoided unless absolutely necessary (and it usually isn't). The better way to do it would be to build the query string in the loop, then execute the query once at the end.

Link to comment
https://forums.phpfreaks.com/topic/240812-foreach-error/#findComment-1236865
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.