tags:

views:

148

answers:

2

hi, I have set my database fields "username" and "email" to unquie, when using the code below this only works if the "username" already exists, an error is then echoed. If they email exists the user gets a mysql duplicate error, when the same error as above should be shown.

<?php

require_once ( 'connection.php' );

$username=$_POST['username']; 
$password=md5($_POST['password']);
$email=($_POST['email']);
$ip=$_SERVER['REMOTE_ADDR'];
session_start();

$query = "INSERT INTO users (username, password, email, rank, ip, active) VALUES     ('$username','$password', '$email', '1', '$ip', '0')";

$sql = "SELECT username AND email FROM users WHERE username = '$username' AND  email     = '$email'" ;
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row = mysql_fetch_array($result);

if ( $count== 0 )
{
if (!mysql_query($query))
{
 die('Error: ' . mysql_error());
}
  echo "You are signed up, please follow the link on your email to active your        account.";
}
else
 {
  echo "Username or Email already exists"."<br><a href=\"sign_up.php\">Try    Again</a></br>";
 }  
?

Thanks

+3  A: 

Try switching

WHERE username = '$username' AND  email     = '$email'"

to

WHERE username = '$username' OR email     = '$email'"

Edit: I'm trying to guess what you're trying to do here. From your description, it seems you want either the username or the email to be unique and you have two separate unique indexes on those columns. Your code checks for the combination of username and email to be unique.

Edit 2: Also, I think you might want to look into the concepts of SQL Injection and Concurrency.

Randolpho
Thanks alot that works fine now =)
also there's no need to do SELECT username AND email... just do SELECT 1 (doing select username AND email does not make any sense)
tehvan
... and please upvote this answer if it helped you
tehvan
Ok thanks, yeh the email and username need to be both uniqueI have also added the function stripslashes and mysql_real_escape_string. To prevent SQL injectionThanks
+1  A: 

Switch to an OR clause in your WHERE statement instead of AND.

Also, DO NOT use the values given in $_POST (or $_GET and $_REQUEST for that matter) without making sure they are safe. What would happen if I sent a username with SQL in it?

','','','','',''); DELETE FROM users;

Make sure you using add_slashes() or a similar process to clean the data before sending to the database.

acrosman
Thanks for the reminderJus added:$username = stripslashes($username);$password = stripslashes($password);$username = mysql_real_escape_string($username);$password = mysql_real_escape_string($password);Should be fine?
Depending on the details the main thing is to use the mysql_real_escape_string() on any text. The md5() on the password should be fine since MD5 never returns text that's a problem. I generally test numbers with is_numeric() to make sure they will work. The stripslashes() is helpful sometimes.
acrosman