Invalid argument supplied for foreach in Internet Explorer only - php

Why is this warning occuring when I am using IE?
Warning: Invalid argument supplied for foreach()
It works in all other browsers..
The function for the loop:
function wdsearch(PDO $dbh){
if(!isset($_POST['wdsubmit'])) {
} else {
$term = $_POST['wdsearchvalue'];
$stmt = $dbh->prepare("
SELECT *
FROM posts
WHERE category = :designer
AND (full_text LIKE CONCAT('%', :term, '%')
OR heading LIKE CONCAT('%', :term, '%'))
ORDER BY post_date DESC
");
$designer = 'Designer';
$stmt->bindParam(":designer", $designer);
$stmt->bindParam(":term", $term);
$stmt->execute();
return $stmt->fetchAll();
}
}
wdsearch($dbh);
$wdsearch = wdsearch($dbh);
And the loop goes here..
<?php foreach($wdsearch as $wds) : ?>
<!-- HTML here -->
<?php endforeach; ?>
Any possible IE related warnings? Like I said all other browsers can handle it..

The problem is in your wdsearch function; if $_POST['wdsubmit'] is not set, it returns nothing and if anything goes wrong in any of the db operations it will not return an array either.
You need to add some error handling to your db operations and in case of failure or a non-post, return an empty array and / or check if $wdsearch is an array before you use foreach.

The specified error is occurring in your PHP code, not in any specific browser.
The issue is, the datatype of $wdsearch, does not implement an iterator. This could be caused by $wdsearch being null, a string/number/etc. - or simply an unsupporting object.
Try verifying if the data is an array before going into the foreach loop with is_array($wdsearch), or verify the variable is not null with isset($wdsearch). If you believe there is valid data there, check to see if the object in $wdsearch actually supports iterators and, if not, update it to implement!
Example:
<?php
if (isset($wdsearch)):
foreach($wdsearch as $wds) :
?>
<!-- HTML here -->
<?php
endforeach;
endif;
?>

If for the same parameters it works in Chrome and FF, but not IE.
What are exactly are you submitting in IE. Is there some silly thing like a button with picture submit? That would pass your terms as the location of the click, not actual value for example.
Debug what your incoming parameters in $POST are before outputting to foreach. Also how do you handle null result sets?

Related

PHP strange behaviour - variables appear unset unless print()ed

I am posting a form to a script with this code:
foreach($_POST as $k=>$v){
if(!is_array($v)){$$k=dbenc($v);} else{$$k=$v;}
$_SESSION["cat"][$k]=$v;
}
$url=vlookup("url","cat","cat=$cat");
// $cat is an integer which originated from the same field value and has been re-posted
"vlookup" is:
function vlookup($field,$table,$criteria){
global $link;
if($table<>""){$from="FROM $table";}
if($criteria<>""){$criteria="WHERE $criteria";}
$r=mysqli_query($link,"SELECT $field as v $from $criteria") or die("VLOOKUP FAILED: $field $from $criteria".mysqli_error($link));
$n=mysqli_num_rows($r);
if($n>0){
$row=mysqli_fetch_assoc($r) or die(mysqli_error($link));
return $row["v"];
}
}
The problem is that
print($cat);exit;
gives the expected result, but $cat does not appear in function output such as
showerror("$cat not found");
and the "vlookup" relying on it produces an error suggesting there is nothing after the =
Printing the query in the error report confirms the absence of the $cat value in the vlookup function.
This makes no sense!
Any thoughts or advice appreciated.
As per my comment above, the problem seems to be the use of false in
if (strpos($value," ")!==false && ...)
after the vlookup using $cat
If I test for spaces without using !==false in combination with other tests, dynamic variables appear as normal. Not sure if this is to be expected?

Unable to produce variable output of type string in multi-lines in PHP

I don't know the correct wording for this issue I am having.
I have a object returned from the database like below:
$pProvisioningFileData->m_fileContent = # Placeholders identified by '${}'
will be replaced during the provisioning
# process, only supported placeholders will be processed.
Dcm.SerialNumber = ${unit.serial_number}
Dcm.MacAddress = ${unit.mac_address}
Dcm.MinSeverity = "Warning"
Cert.TransferHttpsCipherSuite = "CS1"
Cert.TransferHttpsTlsVersion = "TLSv1"
Cert.MinSeverity = "Warning";
The curly brackets are placeholders, the problem I am facing is that when I try output all the content using either echo or print_r, all the content prints in one line however I want to display the content in the same sequence as above.
I tried using var_dump but it also gives some extra info like length and type of variable which I don't want.
So is there a simple way of doing this without using an array?
If you are outputting to browser then wrapping your var_dump in html <pre> tags is quick solution. If you outputting to console then I advise you to install some advanced debuging software. Xdebug comes to mind.
It is difficult from your question to understand exactly what you are wanting to do, but there are three ways you can print out the contents of an object. The third here, looping members, will give you more control and you can add a switch statement or other formatting to output precisely what you desire:
class unit {
var $serial_number;
var $mac_address;
}
$test = new unit;
$test->serial_number = "999";
$test->mac_address = "999.999.999.999";
/* Method 1 - print_r */
print_r($test);
print "\n\n";
/* Method 1 - var_dump */
var_dump($test);
print "\n\n";
/* Method 3 - looping members */
foreach ($test as $memberName => $member)
{
print "{$memberName}: {$member}\n";
}

I need help sorting out an if statement in a simplexml statement

Some basic background ...
I have a form that enters data to an xml file and another page that displays the data from teh xml depending that it meets the requirements . All of this I have managed to get done and thanks to a member on here I got it to show only the data as long as it has todays date and status is out . But I am left with the problem of trying to sort an if statement which needs to show data if it has it or show another div if not .
My Code ...
$lib = simplexml_load_file("sample.xml");
$today = date("m/d/y");
$query = $lib->xpath("//entry[.//date[contains(., '$today')]] | //entry[.//status[contains(., 'out')]]");
foreach($query as $node){
echo "<div id='one'>$node->name</div>
<div id='two'>$node->notes</div>
<div id='three'><div class='front'>$node->comments</div></div>";
}
So to reiterate if query returns matched data do the foreach else show another div
I only wish to know the right code for the if else statement if soneone could help with this I would be very grateful and will up vote any answer as soon as I have the reputation in place . I also apologise in advance if the question has been asked before or if it is too vague thanks again .
If xpath fails to resolve the path, it will return false (see here). Wrap the foreach loop in a simple check:
if( $query ) {
foreach($query as $node){
...
}
}
else {
// Echo the special div.
}
Since PHP is loose typed, if xpath happens to return an empty array, this check will also handle that case. Be aware that if the xpath call does return false, there may be a separate error at play that may require additional or alternative handling.

json encode using php not able to get [] brackets

here is my code
<?
include '../dbConnect.php';
$amp=trim($_POST['amp']);
//$amp='AMP8';
//$sql=mysql_query("select tblRepairQueue.ackNo,tblRepairQueue.repairStatus,tblRepairQueue.savedAt from tblRepairQueue,AMPcustomers where AMPcustomers.phone1=tblRepairQueue.phoneNo and AMPcustomers.id='".$amp."'");
$sql=mysql_query("select phone1 from AMPcustomers where id='".$amp."'");
$response = array();
while($row=mysql_fetch_array($sql))
{
$sql_query=mysql_query("select ackNo,repairStatus,savedAt from tblRepairQueue where phoneNo='".$row['phone1']."'");
while($row1=mysql_fetch_array($sql_query)){
$ackNo=$row1['ackNo'];
$repairStatus=$row1['repairStatus'];
$savedAt=$row1['savedAt'];
$response[]=array('ackNo'=>$ackNo,'repairStatus'=>$repairStatus,'savedAt'=>$savedAt);
}}
print json_encode($response);
?>
output m getting as
{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
but i want the output to look like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]
Can anyone plz help in finding the mistake or what has to be done to get square brackets at the end
This is a bit strange because I have this code:
<?php
$array = array();
$array[] = array("ackNo"=>"26101211236759","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 00:55:25");
$array[] = array("ackNo"=>"26101211236780","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 10:55:25");
echo json_encode($array);
?>
And I get this correct form:
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"26101211236780","repairStatus":"Closed and Complete","savedAt":"2012-10-26 10:55:25"}]
This code should indeed output [{...},...]. So we can't really tell you what went wrong on your side. check the structure of the $response variable before the conversion to Json to see what went wrong.
Note that the code allows SQL injection. You must change it so that the parameters $amp and $row['phone1'] are escaped in the SQL queries. Even if you're relying on magic qoutes now, this solution is not future-proof (now-proof really) as support for this is was removed in PHP 5.4.
What you have written should work:
http://ideone.com/ErV9fr
// How many to add
$response_count=3;
// Your response, just templated
$response_template=array(
'response_number'=>0,
'ackNo'=>'dffdgd',
'repairStatus'=>'$repairStatus',
'savedAt'=>'$savedAt'
);
// Your empty response array
$response = array();
for($i=0;$i<$response_count;$i++) {
$response_template['response_number'] = $i; // Set the 'response number' to the itteration.
$response[]= $response_template; // Add the template to the collection
}
print json_encode($response);
Result:
[{"response_number":0,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":1,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":2,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"}]
In addition to this, you should sanitize your $amp variable. In it's current form it would be trivial for a user to escape your query and execute an arbitrary query against your DB.
http://www.php.net/manual/en/mysqli.real-escape-string.php
Please recheck it can not give you the output like that {"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
as it is creating an array of array so it can not print like that.
It will always print like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]

PHP MySQL Function Displaying in HTML

I have the function:
function get_current_users($current_users)
{
global $db;
$current_users = $db->EscapeString($current_users);
$total_current_users = $db->QueryFetchArray("SELECT COUNT(*) FROM users AS total_current_users");
return $total_current_users['total_current_users'];
}
But I have no clue how to output the result, I've tried the following options but nothing displays:
`<?$total_current_users?>
<?['$total_current_users']?>
<?=data['$total_current_users']?>`
If you are certain that your function does what it's supposed to, I guess the two equivalent methods would gain you the output:
<?= get_current_users() ?> or
<?php echo get_current_users() ?>
As a note: I don't see the point of your argument $current_users that you escape -- because it never gets use in the subsequent query.
Try this syntax
$total_current_users = $db->QueryFetchArray("SELECT COUNT(*) as total_current_users FROM users");
You are selecting one value from inside the result set to return, this value isn't named, try the above to get it to match your code.
then change the template code to be: <?php echo $total_current_users; ?>

Categories