8989
8989

Reputation: 11

PHP if with fetch from Mysql DB

I can't get my head around why this wont work..

<?
(connect info and select DB etc here)

$term = $_POST['term'];
$sql = mysql_query("select * from evansu where username like '%$term%'");
 if ($row==$term)
    {
while ($row = mysql_fetch_array($sql))

      echo 'ID: '.$row['ID'];
    echo '<br/> First Name: '.$row['username'];
    echo '<br/> Last Name: '.$row['name'];
    echo '<br/> Phone: '.$row['Phone'];
    echo '<br/><br/>';
}

else
  echo "Nothing found, have a nice day!";

?>

It says nothing found even if the value is in the DB, and if I remove the if code it works and shows the info. Help?

Upvotes: 1

Views: 66

Answers (4)

DKSan
DKSan

Reputation: 4197

You should have $row = mysql_fetch_array($sql) before checking if your $row['username'] == $term

Upvotes: 0

Ming-Tang
Ming-Tang

Reputation: 17651

Your code is not indented properly and you forgot braces for the while. Also you mixed up the loops.

$term = $_POST['term'];
$sql = mysql_query("select * from evansu where username like '%$term%'");
$row = NULL

while ($row = mysql_fetch_array($sql))
{ if ($row['username']==$term)
    {
      echo 'ID: '.$row['ID'];
      echo '<br/> First Name: '.$row['username'];
      echo '<br/> Last Name: '.$row['name'];
      echo '<br/> Phone: '.$row['Phone'];
      echo '<br/><br/>';
    }
}
if (!$row)
{  echo "Nothing found, have a nice day!"; }

Upvotes: 1

Banago
Banago

Reputation: 1420

You have declared nowhere the variable $row so that you can check against it. So, you basically are checking against a non-existent variable. You should declare the row earlier in the code.

Upvotes: 0

Oswald
Oswald

Reputation: 31655

$row==$term is false if $_POST['term'] is not empty. This leads to the while loop not being executed.

Upvotes: 3

Related Questions