I am trying to check whether or not a new user's username exists in my database. So I typed the code that follows, but for some reason the mysql_query command outputs something like "resource ID # 3" and mysql_num_rows won't accept it. How do I fix this? My database setup looks like this "USERNAMEDB" --> "USERNAMES" --> "NAME" //check used username ($varname == name from field) $loginnametest = $varname; mysql_select_db("USERNAMEDB"); $loginresult = mysql_query("SELECT * FROM USERNAMES WHERE NAME = '$loginnametest';"); $numrows = mysql_num_rows($loginresult); //failed username query if($numrows >= 1) { $usernametaken = "Sorry but the username is already taken."; } else { //continue } Thanks in advance! If you guys need anymore info please tell me. ~Imozeb
Make sure: 1. You've connected to your database sucessfully. 2. $varname exists. 3. Sanitize all data (namely user submitted), when parsing to db. 4. You have a semi-colon at the end of your mysql_query, remove it. Use the following code and report back if any errors appear: <?php error_reporting(E_ALL); $loginnametest = mysql_real_escape_string($varname); $loginresult = mysql_query("SELECT * FROM USERNAMES WHERE NAME = $loginnametest") or die(mysql_error()); $numrows = mysql_num_rows($loginresult) or die(mysql_error()); //failed username query.. if ($numrows >= 1) { echo "Sorry but the username is already taken."; } else { //passed check.. echo "Username does'nt exist"; } ?> PHP:
From a quick look i noticed you have a ; $loginresult = mysql_query("SELECT * FROM USERNAMES WHERE NAME = '$loginnametest';"); Which isn't necessary, try removing it then see if the script works.
1. You've connected to your database sucessfully. (Not sure) 2. $varname exists. (Success) 3. Sanitize all data (namely user submitted), when parsing to db. (Success, already had done that to $varname) 4. You have a semi-colon at the end of your mysql_query, remove it. (OMG how'd that get in there? ) Here are the errors reported: Unknown column 'testname' in 'where clause' So....... what now?
Are you sure the column exists??.... Try this: (although I don't think I've changed any functionality). <?php error_reporting(E_ALL); $loginnametest = mysql_real_escape_string($varname); $loginresult = mysql_query("SELECT * FROM `USERNAMES` WHERE `NAME` = $loginnametest") or die(mysql_error()); $numrows = mysql_num_rows($loginresult) or die(mysql_error()); //failed username query.. if ($numrows >= 1) { echo "Sorry but the username is already taken."; } else { //passed check.. echo "Username does'nt exist"; } ?> PHP:
Change this line $loginresult = mysql_query("SELECT * FROM `USERNAMES` WHERE `NAME` = $loginnametest") to $loginresult = mysql_query("SELECT * FROM `USERNAMES` WHERE `NAME` = '".$loginnametest."'")