Jump to content

How do I search mysql databse for a value?


des1017

Recommended Posts

I'm creating a form that creates a user. I've got a table setup with both username and userpass sections. When I create a user, I want to be able to search the database and know if that user already exists. I've been trying to

$query = SELECT * FROM tablename WHERE userpass = $varpass

then

$result = mysqlquery($query)

 

I was hoping result would either return a username or nothing. then I could set up a if username = $varuser then output username taken. I can't seem to figure out this part.

 

 

$result = mysql_query("SELECT * FROM project WHERE username = $namevar");

if ($result) {

//if ($result == $namevar) {

 

echo "User Taken";

 

} else {

 

mysql_query("INSERT INTO project (username, userpass)

VALUES ('$namevar', '$passvar')");

echo "User Created";

 

}

 

$result needs to be queried. it isn't a very useful thing itself:

 

if (mysql_num_rows($result) > 0) {

   echo "User Taken";

   } else {

   mysql_query("INSERT INTO project (username, userpass) 
   VALUES ('$namevar', '$passvar')");
   echo "User Created";

   }

You want to obtain a count of the number of rows where the username field is equal to the supplied username. This can either be done with the mysql_num_rows() function or, more efficiently, with the sql COUNT function:

 

$result = mysql_query("SELECT COUNT(*) FROM yourtable WHERE username='$username'") or die(mysql_error());
if(mysql_result($result,0) > 0){
  //user name already taken
}else{
 //user not taken -insert into database
}

The manual really is the best place to answer that. The number refers to the row number of the result set. As im sure you can imagine, a lot of queries return more than one row, so the function needs to know which row you are looking at.

 

The manual would also help you with ths kind of thing:

 

thanks, I wasn't sure if the result would have been the actual name or number

 

If you check the page for the function (http://www.php.net/mysql_result) and look at the section called return values, it would help you answer the above question.

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.