Jump to content

mysql_fetch_array, really need to be in a while?


jumpenjuhosaphat

Recommended Posts

The only examples of this that I can find anywhere are:

[code]
while($row=mysql_fetch_array($result))
  {
   
  }
[/code]

Does the mysql_fetch_array really need to be in a while loop?  What if I'm only looking for one field that has my result, and want to ignore the rest?

Could I do this instead:

[code]if(mysql_fetch_array($result))[/code]

What I'm trying to do is find out if the user submitted a username that already exists in the data base.  If it exists, then an error message will be returned.
Well it depends on what your query is really.
For example, if you query any rows where the username in the db matches the user inputted username, and then check the number or rows returned, if its greater than 0 then you know you've got it already and you can give an error to the user, and make them pick again.

[code]
if(mysql_num_rows($result) > 0)
{
-------> Username Exists, give error
}
else
{
-------> No already in db, proceed with script
}
[/code]

So no need to get all the data from the db, and no while loops either.
You do not need to bring back an array, just a row count on the username

$chk_user = mysql_query("SELECT * FROM users WHERE username = '$username'") or die (mysql_error());
$num_user = mysql_num_rows($chk_user);

if(num_user > 0 ){
your error message
exit();
}
if your getting multiple rows from the database, the while statement makes everyones lives easy... if your only to get row... then no...

[code]$result=mysql_query("SELECT * FROM sitewide WHERE `id`='1' LIMIT 1");
$row=mysql_fetch_array($result);[/code]
thats perfectly acceptable.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.