简体   繁体   中英

if compare doesn't work in php

I have a problem with a comparation. I execute this code after execute nmap and saving the pid in the database:

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);

and this is the result:

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

Why does it tell me that are not the same? I don't understand. Thank you in advance.

[SOLVED]

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

Can you try like:

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

There may be some unwanted characters in the data while reading from file.

If you simply want to compare, Sanjay's answer is what you need. But if you want to format the data I would suggest using trim which will strip any characters or whitespace from the value.

while...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM