Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing 2 exact same strings returns false

Tags:

forms

php

mysql

I have a variable that is posted through a html form:

$_POST['ref']

And a variable that is pulled from a table in a database:

$row['ref']

i have a basic comparison script to check if they are both the same:

$ref = $_POST['ref'];

$result = mysql_query("SELECT * FROM logbook.job");
if (!$result) {
    die("Query to show fields from table failed");
}


    $row = mysql_fetch_array($result);
    $refdb = $row['ref'];
    $refform = $_POST['ref'];

    echo $_POST['ref'] ."<br>". $row['ref'] . "<br><br>";

        if ($refdb == $refform) {
    echo "Yes they are<br><br>";
    }

    else {
    echo "No they are not<br><br>";
    }


    if (is_string($_POST['ref'])) 
 {
 echo "Yes";
 } else {
 echo "No";
 }
echo "<br>";
    if (is_string($row['ref'])) 
 {
 echo "Yes";
 } else {
 echo "No";
 }

Which outputs:

G2mtxW
G2mtxW

No they are not

Yes
Yes

I echo them both out. Than i ask if they are the same. Then i check whether each is a string.

How come they are not the same? How can i get them to match

Any help would be appreciated

like image 985
SebastianOpperman Avatar asked Nov 09 '11 11:11

SebastianOpperman


3 Answers

Try using the binary-safe comparison for String:

result = strcmp($str1, $str2);

If the result is 0, then both are the same. Otherwise, they aren't.

like image 176
Kristiono Setyadi Avatar answered Oct 24 '22 10:10

Kristiono Setyadi


One of your strings (probably the one from the DB) might be null-terminated. I've tested the following

$foo = "abc\0";
$bar = "abc";
echo "$foo\n$bar\n";
if($foo == $bar)
  echo "Equal.";
else
  echo "Not equal."

Output is

abc
abc
Not equal.
like image 35
misberner Avatar answered Oct 24 '22 11:10

misberner


Try var_dump-ing both values, check their lengths and inspect them using view-source. They are different in someway.

like image 27
TJHeuvel Avatar answered Oct 24 '22 10:10

TJHeuvel