Elliott
Elliott

Reputation:

duplicate entries mysql and php

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

Upvotes: 1

Views: 976

Answers (2)

acrosman
acrosman

Reputation: 12900

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.

Upvotes: 1

Randolpho
Randolpho

Reputation: 56448

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.

Upvotes: 3

Related Questions