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 聚类分析或者python进行数据分析
  • ¥15 如何用visual studio code实现html页面
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?