dongyang2229 2011-12-20 11:06
浏览 186
已采纳

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

I've created some if / else statements to get name from url like http://website.com/page.php?name=Love It seems to look good and trows no errors, but for some reason I am not getting data from the database. Basically it gets 'name' from url and checks of it is one of allowed categories, if yes it selects article from database that has st_category = to what user selected. But than again for some reason it doesn't work.

Here is a snippet of code that I think causes the problem.

       <?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
?>
  • 写回答

5条回答 默认 最新

  • dtvgo28624 2011-12-20 11:12
    关注

    That could be tidied up to much less code, much more maintainable, using 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"));
    

    And this also fixes the problem that @matino rightly pointed out, which is that you were assigning and not comparing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据