simple php foreach loop help needed - php

I have a for each loop like this
$sn_count = 1;
$prodfilter = "";
foreach($prods as $prod){
$prodfilter .= "<div class=\"product\">".$prod['product'][1]."</div>";
$sn_count++;
}
echo $prodfilter;
Now my problem my "product" class displaying border even if the $prod['product'][1] not available. So i would like to test it using if statement.
If (product value available) {
$prodfilter .= "<div class=\"product\">".$prod['product'][1]."</div>";
}
I tried like this.
if(!empty($prod['product'][1])) {
$prodfilter .= "<div class=\"product\">".$prod['product'][1]."</div>";
}
But its not working.

you can try couple of things
try this for a start
if(strlen(trim($prod['product'][$sn_count]))>0) {
$prodfilter .= "<div class=\"product\">".$prod['product'][$sn_count]."</div>";
}
or
if(isset($prod['product'][$sn_count])) {
$prodfilter .= "<div class=\"product\">".$prod['product'][$sn_count]."</div>";
}

The right thing in my opinion would be to check how many rows returned. I'll assume you are using MySQL since you did not specify. Please ask for additional help if you are not using it.
http://www.php.net/manual/en/function.mysql-num-rows.php
if (mysql_num_rows($prods)!=0) {
//Do your code
}
This should check if your query returned more than 0 rows (so it needs to be drawn). Does it fix it?

The right thing to do is to check if it's empty as you tried, but since it fails there obviously is some data there. You could do a var_dump and figure out what and why it is there which probably leads you to the source of the problem.
If by available you mean declared then isset is the right function to use by the way.

Related

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.

Always get an empty array in foreach loop

There are two columns in the database table "system". I have the systemId and want to get the mobileSystemId. But the variable $mobileSystemIds which I already defined as global is always empty.
EDIT: Now array_map doesn´t work. I always get my Exception output "Arrayfehler ArrayMap"
I have the following code :
$mobileSystemIds=array();
function getMobileSystemId($systemId)
{
global $mysqli;
global $mobileSystemIds;
$query="SELECT mobileSystemId FROM system WHERE systemId ='" .$systemId ."'";
if(!$result=$mysqli->query($query))
{
echo "Datenbankfehler DB-QUery";
exit(0);
}
if (!$mobileSystemId=$result->fetch_assoc())
{
echo "Datenbankfehler DB-Fetch";
exit(0);
}
$mobileSystemId=$mobileSystemId["mobileSystemId"];
echo "mobile System ID: " .$mobileSystemId ."<br />";
return $mobileSystemId;
}
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
In this case, using a return in your function would be much cleaner.
Nothing to do with your problem, but is your $systemId var trusted ? (To prevent SQL injection).
Update:
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
ought to read (just checked; it works for me):
$mobileSystemIds = array_map('getMobileSystemId', $systemsList);
if (empty($mobileSystemIds))
{
if (empty($systemsList) || !(is_array($systemsList)))
echo "OK: no mobile IDs, but no systems either";
else
echo "THIS now is strange :-(";
}
else
{
echo "Alles OK";
var_dump($mobileSystemIds);
}
I tried this by returning a dummy value based on input; if it does not work for you, there must be something strange in the database.
(Update: the text below refers to your original code, which did not use array mapping)
Your code ought to be working as it is. You put several $mobileSystemId 's into a single $mobileSystemId.
It works: I tested with a simpler code, removing the DB calls but leaving your code, and spelling, untouched.
So, the error must be elsewhere. I would guess that this code is included into something else, and:
the $mobileSystemIds = array(); declaration gets executed more than once, thereby losing all its data;
the $mobileSystemIds = array(); declaration is itself included in a more local scope and you read it from outside, reading an empty value or a totally different value.
Try replacing the first part of your code with:
GLOBAL $mobileSystemsIds;
if (defined($mobileSystemsIds))
trigger_error("mobileSystemsId defined more than once", E_USER_ERROR);
else
$mobileSystemsIds = array();
and also, in the function body:
if (!defined($mobileSystemsId))
trigger_error("mobileSystemsId should have been defined", E_USER_ERROR);

PHP mysql check inside a function

I have a function (which I did not write) inside an existing php tag in the head of a page that I've been using for several years the parses URL's and email addresses to make them clickable links:
function ParseURLs($str){
if(isset($str)){
$Output=strip_tags($str);
$Output=preg_replace("/(\swww\.)|(^www\.)/i"," http://www.",$Output);
$Output=preg_replace("/\b(((ftp|http(s?)):\/\/))+([\w.\/&=?\-~%;]+)\b/i"
,"<a href='$1$5' target='_blank' rel='nofollow'>$1$5</a>",$Output);
$Output=preg_replace("/\b([\w.]+)(#)([\w.]+)\b/i"
, "<a href='mailto:$1#$3'>$1#$3</a>",$Output);
return nl2br($Output);
}
}
I wanted to replace the rel='nofollow' with a php check of a MySQL dbase field and have it only put up the rel='nofollow' if the dbase field is empty. I tried to do it by replacing rel='nofollow' in the function with something like this which was my starting point:
<?php if (empty( $row_rswhatever['linkfollow'])) {echo "rel='nofollow'";}?>
or just this:
if (empty( $row_rswhatever['linkfollow'])) {echo "rel='nofollow'";}
I've tried it a hundred different ways (something good usually happens sooner or later) but cannot get it to work. I know from past experience that I am probably missing the boat on more than one issue, and would appreciate any help or guidance. Thanks.
A easy/lazy way to do it would be to continue doing it as you are doing now, however after the last $output=preg_replace add your if test and if you don't want the rel='nofollow', just use str_replace to remove it.
ie.
function ParseURLs($str)
{
if(isset($str)){
$Output=strip_tags($str);
$Output=preg_replace("/(\swww\.)|(^www\.)/i"," http://www.",$Output);
$Output=preg_replace("/\b(((ftp|http(s?)):\/\/))+([\w.\/&=?\-~%;]+)\b/i","<a href='$1$5' target='_blank' rel='nofollow'>$1$5</a>",$Output);
$Output=preg_replace("/\b([\w.]+)(#)([\w.]+)\b/i", "<a href='mailto:$1#$3'>$1#$3</a>",$Output);
if (empty( $row_rswhatever['linkfollow'])) {
$Output = str_replace(" rel='nofollow'", "", $Output);
}
return nl2br($Output);
}
}
Without knowing exactly what you'd be checking for in the database:
function ParseUrls($str) {
$sql = "SELECT ... FROM yourtable WHERE somefield='" . mysql_real_escape_string($str) ."'";
$result = mysql_query($sql) or die(mysql_error());
$rel = (mysql_num_rows($result) == 0) ? ' rel="nowfollow"' : '';
blah blah blah
}
Incidentally, the isset check is useless in your code. The function parameter does not have a default value (function x($y = default)), so if no parameter is specified in the calling code, it will cause a fatal error in PHP anyways.
This also assumes that you've already connected to MySQL elsewhere in your code, and are using the mysql library (not mysqli or pdo or db or whatever else).

PHP EOF showing only one result [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
PHP EOF shows only one result from loop
Hello
Seems like I can not find the solution for such problem.
I am using the following code.
it should display all the results given by the mySQL loop in the EOF.
But it is showing only the first results, nothing else.
What I am doing wrong?
Please help me
function getYiBAdminBanner() {
global $site;
global $dir;
$queryYiBmenu = "SELECT * FROM `(YiB)_cPanel_Menu` WHERE Type = 'top'";
$resultYiBmenu=mysql_query($queryYiBmenu) or die("Errore select menu: ".mysql_error());
$countYiBmenu = mysql_num_rows($resultYiBmenu);
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
$menu .= "<div id=\"menu\" style=\"display:none;\"><li><img class=\"imgmenu\" src=\"".$site['url'].$rowYiBmenu['linkIcon']."\">".$rowYiBmenu['linkTitle']."</li></div>";
}
if($countYiBmenu <= 0){
$menu = "No Modules Installed";
}
$bannerCode .= <<<EOF
<div style="width:520px; background-color: #EEE; height:30px;">
{$menu}
</div>
EOF;
return $bannerCode;
}
Though this won't fix your issue, I see you are using mysql_fetch_array(). This is rather pointless, as you are doing associative matching afterwards ($rowYiBmenu['linkHref'], for example). It will work for you, but it's a waste of resources, as the results will be loaded in a numeric array as well (making the $rowYiBmenu array twice as large, just wasting memory).
Also, you didn't declare the $menu variable, you just 'added on'. Before the while statement, put $menu = ''; (or anything else that will declare an empty string for that variable).
Lastly, use single quotes around html strings. That way you don't have to keep escaping double quotes for when adding an attribute. For example, the $menu line in the while statement should look like this:
$menu .= '<div id="menu" style="display:none;"><li><img class="imgmenu" src="'.$site['url'].$rowYiBmenu['linkIcon'].'">'.$rowYiBmenu['linkTitle'].'</li></div>';
I'm not sure if I helped you with your problem at all, but I thought this would help you clean up your code a bit (the cleaner the code, the less prone to errors and the easier it is to spot errors).
I have tried helping in the other duplicate question.
i feel you need to implement (learn?) some basic debugging on the data coming from the database. This should be very simple to solve.
I suggest changing your while() code to something like this to help debug whats happening:
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
print "linkTitle: " . $rowYiBmenu['linkTitle'] ."<BR>";
print "linkHref: " . $rowYiBmenu['linkHref'] ."<BR><BR>";
}
exit;
You should see output of all results from the database (not just the first or last). After establishing that the correct data is being retrieved and looped through. you can get that $menu variable concatenation and $bannerCode + HereDoc EOF code sorted out.

Using a Loop Inside a Function

I'm still learning functions and how they work. I know what I'm doing wrong just not how to fix it. I am writing a function to pull image data out of a database and return it onto the screen. It works but if there is more than one image it will return the last image only. I know the problem is that $project_image is only returning the last image because of the way the while loop works but my question is how can i either not use a while loop or make it add more than one image to the $project_image variable.
Abridged Function
function get_project_image($id,$type="thumb",$src="false",$limit=1){
if($type =="main"){
$project_image_qry = mysql_query(" SELECT i_name FROM `project_images` WHERE i_project_id = '$id' AND i_type= '2' LIMIT $limit " ) or die(mysql_error());
$project_image="";
while($project_image_row = mysql_fetch_array($project_image_qry)) {
$project_image_result = mysql_fetch_array ($project_image_qry);
if($src=="true"){
$project_image .= '<img src="'.admin_settings('site_url').admin_settings('image_main_dir').'/'.$project_image_result['i_name'].'" alt="project_image"/>';
}
else{
$project_image .= $project_image_result['i_name'];
}
}
}
return $project_image;
}
Your while condition is fine, but you seem to be fetching twice, in $project_image_row and $project_image_result, so you're going to be skipping every other image. Just fetch the array once (in the while loop is good), and use $project_image_result instead of $project_image_row within the loop to refer to that array:
while($project_image_result = mysql_fetch_array($project_image_qry)) {
if($src=="true"){
$project_image .= '<img src="'.admin_settings('site_url').admin_settings('image_main_dir').'/'.$project_image_result['i_name'].'" alt="project_image"/>';
}
else{
$project_image .= $project_image_result['i_name'];
}
}
Also, it seems like by default you told it to only request one image from the database. You have a default parameter $limit=1, and you use an SQL LIMIT to filter the results, so unless you pass a fourth argument to get_project_image the mysql_query is only going to return one result (you didn't include the call to get_project_image, so I'm not sure if you handled that or not

Categories