Jump to content

Not sure why


SkyRanger

Recommended Posts

Not sure why the else would not show:

 

$resultc = mysql_query("SELECT * FROM table where mpid=$mpid");

while($rowc = mysql_fetch_array($resultc))

if($mpid == $rowc['mpid']) {
        echo '<p>' . $rowc['vpcomm'] . '</p>';
} else {
        echo "No Comments Available";
}

 

What I am trying to do for example is

 

if $mpid = 6 and rowc['mpid'] = 6 then vpcomm displays (This works already)

 

but if rowc['mpid'] does not contact (6) then it would echo no comments.

 

 

Link to comment
https://forums.phpfreaks.com/topic/259716-not-sure-why/
Share on other sites

My assumption, is on your while loop, you have no curly braces.

 

When a if / else statement runs, it will only read the next line, and disband the others as if it doesnt exist.

 

//this will work!
while($i < 10){
return $i;
i++
}

//This one will be an infinate Loop!! D=
while($i < 10)
return $i;
i++

 

as you notice, the first one has curly braces. But the second one does not. It will be an infinate loop. BECAUSE without curly braces it will only return the next statement. However, everything inside the curly braces will be executed as part of that statement.

 

 

So techinally your code is only checked to see if those variables actually match. That's just about it.

Link to comment
https://forums.phpfreaks.com/topic/259716-not-sure-why/#findComment-1331104
Share on other sites

In the provided code, the WHILE loop contains a single statement. It is an IF statement. Since it is a single statement, the curly-braces are not technically required. Just like an IF statement without braces will execute a single statement, so will a WHILE. The reason that the ELSE part is never getting executed is that the statements inside the example loop never execute when mpid != $mpid.

 

Since the SELECT statement will not return any rows, the condition on the WHILE loop is false, and the IF is not executed. To get the desired results, try something like this:

 

$resultc = mysql_query("SELECT * FROM table where mpid=$mpid");

if (mysql_num_rows($resultc)) {
  while($rowc = mysql_fetch_array($resultc))
        echo '<p>' . $rowc['vpcomm'] . '</p>';
} else {
        echo "No Comments Available";
}

 

again, without the curly-braces, it is a bit confusing, so:

 

$resultc = mysql_query("SELECT * FROM table where mpid=$mpid");

if (mysql_num_rows($resultc)) {
  while($rowc = mysql_fetch_array($resultc)) {
        echo '<p>' . $rowc['vpcomm'] . '</p>';
  }
} else {
        echo "No Comments Available";
}

 

Link to comment
https://forums.phpfreaks.com/topic/259716-not-sure-why/#findComment-1331113
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.