[SOLVED] What am I doing wrong?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Lan
Forum Newbie
Posts: 2
Joined: Mon Mar 15, 2004 6:24 am

[SOLVED] What am I doing wrong?

Post by Lan »

Hello. I am relativly new to php coding. I have been wanting to make my site dynamic based on if the person is a registered user in my message board database or not. I'm sure there is probably many pre made scripts I could use if I wanted to, but I also wanted to learn php anyway.

So I started writing a test page to get the hang of querying the database. I finnally got it to work. However, If I try and enter a username that I know is not in the database, it won't print the output saying that the user is in the database.

It will output if the user is in the database, but not the oposite. Can someone help me out here?


Here is the code...

Code: Select all

$username=$_POST['u_name'];


$db=mysql_connect("localhost","****","*******") or die (mysql_error());

mysql_select_db("myforum",$db) or die ('Cannot select database : ' . mysql_error());

$query=mysql_query("SELECT * FROM ibf_members WHERE name='$username'");
if (!$query) {
    die ('Invalid query : ' . mysql_error());
}


while ($db_name=mysql_fetch_array($query)) {
	if ($username == $db_name[name]) {
        print "It works! $username is in the database!";

    } 
    else {
           print "$username is not in the database";

    } 

} 
mysql_close();
Any help for this newbie would be greatly appreciated.............Lan
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

Try something like...

Code: Select all

$username= $_POST['u_name'];

$db = mysql_connect('localhost', '****', '*******') or die (mysql_error());

mysql_select_db('myforum') or die ('Cannot select database : ' . mysql_error());
$query = "SELECT * FROM ibf_members WHERE name='$username'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result) == 0){
  echo $username.' is not in the database.';
} else {
  $db_name = mysql_fetch_assoc($result);
  echo $db_name['name'].' is in the database.';
}

mysql_close();
Lan
Forum Newbie
Posts: 2
Joined: Mon Mar 15, 2004 6:24 am

Post by Lan »

Sorry about the long wait. But that worked.

Can anyone enlighten me as to why the replacement code worked, but mine did not? Knowing would help me out a lot. Thanks!...............Lan
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

You had, while ($db_name=mysql_fetch_array($query)) { , so if the username didn't exist in the database then there would be nothing to fetch and it would never go into the while loop, and therefore never reach the if{}else{} you had.
Post Reply