开发者

elseif not working

This doesn't make sense.. I'm trying to sort posts according to the value of a URL parameter but my elseif statement isn't working.

This is a function that adds another WHERE clause to the query. There are no MYSQL errors I'm just having statement trouble.

function sort_where($where)
{
  if (isset($_GET['sort'])) { 
      $sort = $_GET['sort'];

      if ($sort = "up") {
         $where .= " AND $sort > 1";
      } 
      elseif ($sort = "down") {
         $where .= " AND $sort &g开发者_高级运维t; 1";
      }

   }

  return $where;
}

The query eventually looks like this

$query = "SELECT * FROM posts WHERE something = $something AND $sort > 1";

The if statement works, the elseif is ignored. I get posts with up > 1 regardless or vice-versa if $sort = down in the if statement.


Actually, neither of the two inner ifs are working correctly.

You need to use == not =. One equals sign means assignment, and if you assign to a truthy value it always evaluates to true in an if condition. That's why your elseif appears to never happen.

You may also need to fix your WHERE clauses, they don't make sense to me (you're sorting but comparing to an up column and a down column?). Or maybe that's how you designed your table...


Based on your comments, try the following SQL WHERE clauses and see if you get the correct posts:

if ($sort == "up") {
   $where .= " AND up > down";
} 
elseif ($sort == "down") {
   $where .= " AND down > up";
}


Single = means variable 1 = variable 2

Double == means compare

Also if you are going to use this code make sure you put mysql_real_escape_string() around your $_GET statements or anything that has user inputs or people will be able to use sql injection.

E.g. mysql_real_escape_string($_GET['sort']) and if you are using it multiple times makes sure you use a variable

Here is the corrected code ;)

function sort_where($where)
{
  if (isset($_GET['sort'])) { 
      $sort = $_GET['sort'];

      if ($sort == "up") {
         $where .= " AND $sort > 1";
      } 
      elseif ($sort == "down") {
         $where .= " AND $sort > 1";
      }

   }

  return $where;
}


Two problems:

  if ($sort = "up") {

= is the assignment operator. You need to use == here if you want to test for equality.

Also, the body of both conditionals:

  if ($sort = "up") {
     $where .= " AND $sort > 1";
  } 
  elseif ($sort = "down") {
     $where .= " AND $sort > 1";
  }

Are identical. I don't think you mean to append the same basic string to the query, do you? (Granted $sort will be different in either case, but why not just hardcode the strings in if that's what you mean anyway. This just reads really confusing, and it's hard to tell exactly what your intent is.)


if ($sort = "up")
elseif ($sort = "down")

should be

if ($sort == "up")
elseif ($sort == "down")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜