Page 1 of 1

[SOLVED] What am I doing wrong?

Posted: Mon Mar 15, 2004 6:24 am
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

Posted: Mon Mar 15, 2004 6:58 am
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();

Posted: Thu Mar 18, 2004 4:49 am
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

Posted: Thu Mar 18, 2004 8:15 am
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.