2017-04-03 35 views
-2

我想通過使用GET參數從我的數據庫中獲取信息。問題是,只要$_GET['archived']設置爲yes它仍然執行no/!isSet部分。否則,如果語句不工作使用GET參數

if(isSet($_GET['archived']) == "no" || !isSet($_GET['archived'])){ 
     // find out how many rows are in the table 
     $r = $connection->prepare(" 
      SELECT * 
      FROM categories 
      WHERE archived='no' 
     "); 
    } else if(isSet($_GET['archived']) == "yes"){ 
     // find out how many rows are in the table 
     $r = $connection->prepare(" 
      SELECT * 
      FROM categories 
      WHERE archived='yes' 
     "); 
    } 
+0

你從哪裏知道'isset()'會返回'no'或'yes'?再次檢查您的代碼。 http://php.net/manual/en/function.isset.php – JustOnUnderMillions

+0

如果$ _GET設置爲「否」,但它不會工作,但如果設置爲「是」,則不會。 – Supahotfire420

+0

** isset **返回** true **或** false ** –

回答

0

isset運營商返回truefalse。所以,你必須修改你這樣的代碼:

if ((isset($_GET['archived']) && $_GET['archived'] == "no") || !isset($_GET['archived'])) { 
    // find out how many rows are in the table 
    $r = $connection->prepare(" 
      SELECT * 
      FROM categories 
      WHERE archived='no' 
     "); 
} else { 
    if (isset($_GET['archived']) && $_GET['archived'] == "yes") { 
     // find out how many rows are in the table 
     $r = $connection->prepare(" 
      SELECT * 
      FROM categories 
      WHERE archived='yes' 
     "); 
    } 
} 
-1

簡單,但工程:)

if (!isset($_GET['archived'] || $_GET['archived'] == 'no')){ 
     // find out how many rows are in the table 
     $r = $connection->prepare(" 
      SELECT * 
      FROM categories 
      WHERE archived='no' 
     "); 
    } 
    if ($_GET['archived'] == 'yes') { 
     $r = $connection->prepare(" 
      SELECT * 
      FROM categories 
      WHERE archived='no' 
     "); 
    } 

另外,如果你使用一些框架,不採取GET/POST權從 '魔力' 的變量。

+0

看問題中的第一行代碼。有**的條件! isset ** –

-1

你比較結果isset()函數功能串「不」和「是」的。但是,isset將返回一個布爾值

刪除isset()函數將導致下面的代碼塊:

if($_GET['archived'] == "no") { 
    // find out how many rows are in the table 
    $r = $connection->prepare(" 
     SELECT * 
     FROM categories 
     WHERE archived='no' 
    "); 
} else if($_GET['archived'] == "yes") { 
    // find out how many rows are in the table 
    $r = $connection->prepare(" 
     SELECT * 
     FROM categories 
     WHERE archived='yes' 
    "); 
} 

請注意,你應該總是做一些預處理從一個(不信任)客戶端接收的值,例如$ _GET和$ _POST,以減輕注射風險。

背景:isset()只會幫助您確定是否設置了值。這種類型的語言功能通常在非靜態類型的編程語言中是必需的。

由於您將isset()函數的結果與字符串進行比較,因此要求PHP將一個布爾值與該字符串進行比較。

official PHP site

isset — Determine if a variable is set and is not NULL 

TL; DR: Isset爲如果一個值被設置檢查最有用。不要用它來比較你期望的實際值。

+0

您的示例不確定$ _GET ['archived']何時不存在。所以當在E_ALL中設置error_reporting時,你會看到'未定義的變量' –