2015-06-11 46 views
2

我有一個比較問題。我執行此代碼執行nmap並在數據庫中保存pid後:如果比較不起作用在php

include("classes/database.php"); //conection to database 

$selectActual = "SELECT * from InfActual"; 
$resultActual = $conn->query($selectActual); 
if ($resultActual->num_rows > 0) { 
    while ($rowActual = $resultActual->fetch_assoc()) { 
     echo "pid in DB: " . $rowActual['pid'] . "<br>"; 

     echo "................<br>"; 

     exec("pgrep -l 'nmap' | cut -d' ' -f1 > pids.txt"); 

     $fh = fopen('pids.txt', 'r'); 

     while ($line = fgets($fh)) { 
      if ($line == $rowActual['pid']) { 
       echo "pid in pids.txt: " . $line . " and pid in DB: " . $rowActual['pid'] . " are the same <br>"; 
      } else { 
       echo "pid in pids.txt: " . $line . " and pid in DB: " . $rowActual['pid'] . " are NOT the same <br>"; 
      } 
     } 
    } 
} 
fclose($fh); 

,這是結果:

pid in DB: 5926 
................ 
pid in pids.txt: 5926 and pid in DB: 5926 are NOT the same 

爲什麼它告訴我,是不是一樣的?我不明白。 預先感謝您。

[解決]

if (intval($line) == intval($rowActual['pid'])) 
+1

問題可能是因爲您的文本文件中每行的末尾都有一個換行符('\ n')。所以:'「xy \ n」===「xy」'不會和你所看到的一樣。 (解決方法?只需從文件中修剪()你的行,例如'if(trim($ line)== $ rowActual ['pid'])') – Rizier123

+0

謝謝,現在工作正常:) – Safira

+0

不客氣。 – Rizier123

回答

3

你可以嘗試這樣的:

if (intval($line) == intval($rowActual['pid'])) {...} 

可能存在的一些數據不需要的字符,而從文件中讀取。

+0

謝謝你,你的解決方案也可以:) – Safira

0

如果你只是想比較,桑傑的答案是你所需要的。但是,如果你想格式化數據,我建議使用trim,這將刪除值的任何字符或空格。

while... 

$line = trim($line); 
$rowActual['pid'] = trim($rowActual['pid']); 

if ($line == $rowActual['pid']) {...} 
+0

感謝您的提示:) – Safira