2012-07-13 326 views
0

我有這個代碼,它有一個錯誤,但我不明白我出錯的地方。有人可以幫忙嗎?問題是,我試圖顯示一個特定的圖像來腐蝕文本文件的內容。我覺得我有這部分排序,但是當涉及到顯示圖像總有一個錯誤(例如,它永遠是綠色的,即使如果statment說otherwize.Here是代碼:PHP - 如果和其他語句

<?php 
      if (empty($_GET['unit'])) { 
      $output="Please Enter A Unit Number"; 
      echo $output; 
      } 
      else { 
       $filepathhalf = "/data/"; 
       $file = "false"; 
       $date = date("Ymd"); 
       $unitnum = $_GET['unit']; 
       $ext = ".txt"; 
       $filepath = $filepathhalf.$unitnum.$date.$ext; 
       echo $filepath; 
       echo $file; 
       if(file_exists($filepath)) 
       { 
        $fh = fopen($filepath, 'r'); 
        $file = fread($fh, 5); 
        fclose($fh); 
       } 
       echo $file; //This echo comes back as false as set but the green.png image still displays. 
       if ($file = "true ") 
       { 
        echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />"; 
       }     
       else 
       { 
        echo "<img src=\"images/red.png\" width=\"15\" height=\"15\" />"; 
       } 
       echo $_GET['unit']; 
      } 
      ?> 
+0

三江源指點大家指出了這一點:)生病接受第一次的答案只是因爲我只能accpept一個.. – Nick 2012-07-13 05:27:15

+1

雖然你不應該在一個文件中混合的擔憂,不管怎麼說,你可能會發現PHP輸入和輸出HTML輸出有利:'if($ file):?> Dan 2012-07-13 05:56:39

回答

4

是有區別的。比較兩個實例,並指定一個到另一個之間

請參見下面的行從您的片段,看看你可能會看到錯誤與上面的線索:

if ($file = "true ") 
{ 
    echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />"; 
}     
else 
{ 
    echo "<img src=\"images/red.png\" width=\"15\" height=\"15\" />"; 
} 

否則你的鼠標懸停在懸停下面的擾流板!

如果你想關於這個問題的解釋,做同樣的...

$file = "true "將始終爲true,首先它 將分配的字符串「true」$file,然後將評估值 $file

你最可能尋找if($file == true),這將$file值比較true

+0

乾杯:)現在開始! – Nick 2012-07-13 05:28:16

+1

+1爲擾流板! :))) – alfasin 2012-07-13 05:30:32

+0

@Nicholas沒問題的隊友,很高興能成爲服務! – 2012-07-13 05:32:31

3

您使用一個單獨的=,它用於分配變量時,不進行比較。在檢查兩個值是否相等時,請使用==

2
if ($file == true) 
    { 
      echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />"; 
    } 

希望幫助

1

應該==檢查條件。

if ($file != "false") 
{ 
    echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />"; 
} 
1

不僅你使用單個「=」,而且還將它與「真實」(連接空間!)進行比較。我會改變代碼:

if ($file === true) 
{ 
    echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />"; 
}