views:

676

answers:

3

When a user creates an account on my website, i want the inputted username to be checked against all the current usernames in my database(MySQL) and confirmed if it is available.

Does anyone know any good libraries i could use, or a plug-in for JQuery perhaps?

Thanks, Ben.

A: 

Create a PHP file that takes the username as an argument. Then pass it through a $.get method in jquery. This then returns a variable (in my case called data) That variable will contain anything the PHP file printed.

$.get("ajax_available.php?u="+username, function(data){
 if(data == "true")
 {
     // username avaiable
            $("#usernameAlert").html("<img src='images/icons/accept.png' 
               title='Laust' /> Username available");
 }
 else
 {
     // username not avaiable
 }
});

In this example my php file returns the string "true" but thats just a quick example.

Ólafur Waage
+1  A: 

And this is untested code that is the server-side

<?php
// check_username_available.php?name=(name they supplied)

// this stuff is normally in config.inc.php
$username = "...";  // Mysql username 
$password = "...";  // Mysql password 
$db_name = "...";   // Database name 

// get name supplied from querystring
$name = $_GET('name');

// Connect to server and select database.
//
mysql_connect("localhost", $username, $password) or die("cannot connect to db"); 
mysql_select_db($db_name) or die("cannot select $db_name DB");

$query = "SELECT COUNT(*) FROM 'users' WHERE user_name = '$name'";
$result = mysql_query($query) or die("cannot count rows: " . mysql_error());

header("Content-Type: text/plain");
echo ( 0 < mysql_result($result, 0) ? "false" : "true" );
Scott Evernden
A: 

Exactly what you want is given in example form here. it uses jQuery as the JavaScript library

Shane O'Grady