I have the following PHP code to retrieve the hometown of a user in a MySQL database:
$query = "SELECT hometown FROM members WHERE username = '$username'";
$result = mysql_query($query) or die(mysql_error());
However, I want to determine whether there are any results before attempting to display them. But I don't know what to test for in an "if" statement.
Currently, the following code prints much the same thing whether the user exists or not:
echo 'username = ' . $username . '<br />';
$query = "SELECT hometown FROM members WHERE username = '$username'";
echo '<br />result = ' . $result . '<br />';
echo '<br /><b>m_f_a(result) = ' . mysql_fetch_assoc($result) . '</b><br />';
echo '<br />count(m_f_a(result)) = ' . count(mysql_fetch_assoc($result)) . '<br />';
echo '<br />sizeof(m_f_a(result)) = ' . sizeof(mysql_fetch_assoc($result)) . '<br />';
As you can see in the output here, an array only seems to be created and assigned to $result if the username exists, but the length of $result is always given as 1 regardless:
username = realusername
result = Resource id #3
m_f_a(result) = Array
count(m_f_a(result)) = 1
sizeof(m_f_a(result)) = 1
username = fakeusername
result = Resource id #3
m_f_a(result) =
count(m_f_a(result)) = 1
sizeof(m_f_a(result)) = 1
What should I be testing for? I've tried if(!$result) and if(!isset($result)), amongst several other permutations, but can't seem to create a different course of action for my script based on whether a result was found or not. I'm sure it's something really simple...