PHP if/else语句似乎不起作用

Ilj*_*lja 0 php mysql if-statement

我已经创建了一些if/else语句来从URL获取名称,如http://website.com/page.php?name=Love它看起来很好看并且没有错误,但由于某种原因我没有从中获取数据数据库.基本上它从url获取'name'并且检查它是允许的类别之一,如果是,它从具有st_category =的数据库中选择文章到用户选择的内容.但是由于某些原因,它不起作用.

以下是我认为导致问题的代码片段.

       <?php
        $category = preg_replace('#[^a-z]#i', '', $_GET["name"]);

        if ($category = "Love") {
        $st_category = "Love";
        }
        else if ($category = "Work") {
        $st_category = "Work";
        }
        else if ($category = "Money") {
        $st_category = "Money";
        }
        else if ($category = "Kids") {
        $st_category = "Kids";
        }
        else if ($category = "Health") {
        $st_category = "Health";
        }
        else if ($category = "Friends") {
        $st_category = "Friends";
        }
        else if ($category = "Education") {
        $st_category = "Education";
        }
        else if ($category = "Other") {
        $st_category = "Other";
        }
        else {
        header("Location: http://www.inelmo.com/");
        exit;
        }

$sql = mysql_query("SELECT * FROM stories WHERE showing = 1 AND st_category = '$st_category' ORDER BY st_date DESC LIMIT 10") or die (mysql_error("There was an error in connection"));
        //And another stuff here to display article
?>
Run Code Online (Sandbox Code Playgroud)

mat*_*ino 9

=是不一样的==.在你的if语句中,你正在进行分配而不是比较.
if ($category = "Love")应改为if ($category == "Love")(或if ($category === "Love")等等......)


Dav*_*dom 7

这可以整理到更少的代码,更易于维护,使用in_array().

$categories = array(
  'Love',
  'Work',
  'Money',
  'Kids',
  'Health',
  'Friends',
  'Education',
  'Other'
);

$category = preg_replace('#[^a-z]#i', '', $_GET["name"]);

if (!in_array($category, $categories)) {
  header("Location: http://www.inelmo.com/");
  exit;
}

$sql = mysql_query("SELECT * FROM stories WHERE showing = 1 AND st_category = '$category' ORDER BY st_date DESC LIMIT 10") or die (mysql_error("There was an error in connection"));
Run Code Online (Sandbox Code Playgroud)

这也解决了@matino正确指出的问题,即你分配而不是比较.