2013-07-19 16 views
5

Ho creato un sistema di login/registrazione e sto avvicinandomi per completare la parte di codice del mio registro. L'unico problema che sto incontrando è come farlo in modo che gli utenti non possano registrarsi con nomi utente duplicati. Voglio che funzioni affinché il mio database non accetti le informazioni e informerà l'utente sull'errore. Qualsiasi aiuto è apprezzato.Come evitare i nomi utente duplicati quando le persone si registrano? PHP/MySQL

mio PHP

<?php 
include ('database_connection.php'); 
if (isset($_POST['formsubmitted'])) { 
$error = array();//Declare An Array to store any error message 
if (empty($_POST['name'])) {//if no name has been supplied 
    $error[] = 'Please Enter a name ';//add to array "error" 
} else { 
    $name = $_POST['name'];//else assign it a variable 
} 

if (empty($_POST['e-mail'])) { 
    $error[] = 'Please Enter your Email '; 
} else { 


    if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) { 
     //regular expression for email validation 
     $Email = $_POST['e-mail']; 
    } else { 
     $error[] = 'Your EMail Address is invalid '; 
    } 


} 


if (empty($_POST['Password'])) { 
    $error[] = 'Please Enter Your Password '; 
} else { 
    $Password = $_POST['Password']; 
} 


if (empty($error)) //send to Database if there's no error ' 

risposta

7

Si può fare in questo modo quando l'utente inviare il nome utente per esempio e fare clic su Invia si può scrivere questo codice o aggiungerlo al tuo codice con il vostro modifica:

<?php 
$connect = mysql_connect('whatever','whatever','whatever'); 
$database = mysql_select_db('your dbname'); 
$username = $_POST['username']; 
if(isset($username)){ 
$mysql_get_users = mysql_query("SELECT * FROM table_name where username='$username'"); 

$get_rows = mysql_affected_rows($connect); 

if($get_rows >=1){ 
echo "user exists"; 
die(); 
} 

else{ 
echo "user do not exists"; 
} 



} 
?> 
+0

Ci scusiamo per l'attesa, ma questo ha risolto il mio problema perfettamente! L'ho inserito nel mio codice circa 10 minuti fa e non accetterà più nomi utente duplicati e produrrà un errore. – Zippylicious

+0

grazie mille per + rep per me, e sono felice che questa risposta abbia funzionato per te, ma voglio dirti qualcosa, quando crei la colonna dell'utente puoi renderla unica, ad esempio creare utenti di tabelle (nome utente varchar (350) non null unique), buona fortuna :) –

1

Penso che qualcosa di simile a questo è quello che stai cercando:

if (isset($_POST['user'])) 
{ 
    $user = $_POST['user']; 

    if (mysql_num_rows(yourFunctionForQueryingMySQL("SELECT * FROM tablename WHERE user='$user'"))) 
      echo "Name is taken"; 
    else echo "Name available"; 
} 
1

ci sono due cose dovresti fare.

  1. Rendere il nome utente una chiave primaria nella tabella del database. Questo è fatto facilmente usando phpmyadmin.

  2. Convalidare prima di inserire.

Per il secondo passaggio, ecco un algoritmo. Puoi implementarlo a modo tuo usando pdo, mysqli o anche mysql (anche se non è raccomandato ora).

Algoritmo alla fine del codice (vale a dire, se non ci sono errori) ...

Selezionare i record che corrispondono al username fornito nel post.

Se esiste, genera un errore.

Se non esiste, inseriscilo.

Spero che questo aiuti.

0

È necessario (possibile) rendere condizione che vieta la registrazione se il nome utente esiste già.

$sql="SELECT username FROM tablename WHERE username='".$username."'";//looking through existing usernames 
    $resul=mysql_query($sql); 
    $num = mysql_num_rows($resul); 

    if ($num !=0){ //If there is already such username... 

    die("There is user with that username."); // ...kill the script! 
} else //continue with the script 
0

Ho usato un PDO e un metodo di classe, potrebbe essere di qualche utilità.

//function for checking if the user already exists in the database 
public function userExists($username){ 

//prepared statements for added security 
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?"); 
$query->bindValue(1, $username); 

try{ 
    //execute the query 
    $query->execute(); 
    $rows = $query->fetchColumn(); 

    //if a row is returned...user already exists 
    if($rows == 1){ 
     return true; 
    }else{ 
     return false; 
    } 
//catch the exception 
}catch (PDOException $e){ 
    die($e->getMessage()); 
} 
}//end function userExists 

nota le dichiarazioni preparate troppo - sicuramente la strada da seguire

0

si può fare in questo modo:

<?php 

//---put this code before "if (empty($error))"------ 

$username = $_POST['username']; 
//---if your table user is "table_user" and fieldname username is "username" 
$query = 'SELECT username FROM table_user WHERE username = "' . $username . '" LIMIT 1'; 
$result = mysql_query($query) 
$totalNumRowResult = mysql_num_rows($result); 

if($totalNumRowResult > 0) { 
    $error[] = 'User exist'; 
} 

?> 

Speranza che aiuta.

Problemi correlati