views:

69

answers:

2

I have created a form and have validated everything using PHP, but can't figure out how to validate email from database. If I have the entered username in the database, I want it to display an error. I have connect.php and

just for an example -

here's how i validate password -

if(!empty($_POST['password']))
{
 if($_POST['password'] != $_POST['cpass']) 
 {
  $errors[] = 'The password and confirm password do not match.';
 }
 else
 {
  $p=trim($_POST['password']);
 }
}

here is what i'm trying to do -

$getusername = "SELECT username FROM users WHERE ($u,$username)";
if($getusername)
{
    echo 'Username is already in use.';
}
else
{
    $g=trim($_POST['username']);

}

THIS RESULTS IN A PARSE ERROR.

A: 

To run a query against the database you need to use php-mysql libraries. Here is an example:

$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$sql = "SELECT * FROM Person";
mysql_query($sql,$con);

// some code

mysql_close($con);

http://www.w3schools.com/php/func_mysql_query.asp

Make sure you run all your parameter through mysql_real_escape_string to protected against sql injection!

Amir Raminfar
+1  A: 
// first define the username from the $_POST variable
// make sure to escape the value to prevent SQL injection
$username = mysql_real_escape_string(trim($_POST['username']));

// select a user with the posted username
$sql = "SELECT username FROM users WHERE username = '$username' LIMIT 1";

// run the query
$res = mysql_query($sql) or die(mysql_error());

// see if there's a result
if (mysql_num_rows($res) > 0) {
  echo 'This username is already taken';
} else {
  // .. do stuff
}
Alec
oh my god....thank you so much..it worked..vote up for best answer.
Johnson
As I am a beginner, could you explain why u used LIMIT 1? Thanks.
Johnson
There are various ways [LIMIT](http://dev.mysql.com/doc/refman/5.0/en/limit-optimization.html) can be used, but in this case the idea is that the query can be aborted when a single result has been found. Since we're looking for possible duplicates, a single result would already be enough for us to determine that there _is_ a dupe; there's no point in searching any further. In this case it probably won't make much of a difference in speed, but if you're searching through a huge list of records, it might make a difference.
Alec