how to let user know that name already exists
New programmer- I have created a function to add a user to a database. This function is found in class USER. I have set up mysql to have user_name as a unique key. If a user tries to enter a name that already exists it is not entered into the mysql database but my form says ok its been submitted and just moves to the next page. I want to let the user know that the name already exists and create an error on the registration form. Is there a way to append that to this function?
function add_member($name, $email, $password)
{
global $mysqli;
$query = "INSERT INTO members
SET
user_name = '".addslashes($name)."',
user_email = '".addslashes($email)."',
password = '". md5($password) ."'";
$success = $mysqli->query ($query);
if (!$success || $mysqli -> affected_rows == 0)
{
echo "<p> An error occurred: you just are not tough enough!!! </p>";
return FALSE;
}
$uid = $mysqli -> insert_id;
return $uid;
开发者_运维百科 if (!$found_error)
{
header("location: homepage.php");
}
In order to prevent the redirect, you have to inform your front end that there's been an error.
Your form will always attempt to "move to the next page" whenever a user clicks "submit." It will do whatever action is set.
In that action (which I assume is the next page in the process), you should have the page handle the error - i.e. :
<?php //results.php
if(false === add_member($name, $email, $password)){
//you may want to write code that sends post data with error type here...
header("location:create_user.php");
}
?>
note that using header-redirects is somewhat inelegant, but the best practices of how to handle error is out of scope of this question...
My point is, you must catch the error on your result page, and have that page handle a failed attempt.
You are close, but instead of just doing the insert, try checking for user first by doing a select on the name. If the record count is greater than zero you know that it already exists.
Then either either put up a javascript alert or send it to antother page if it already exists, otherwise go ahead and do the insert. This way you aren't relying on the database to do the check for you and you then have more control of what happens next.
Good luck and HTH -- Joe
Why don't you make an Ajax call after the user enter his desired Username to check if it's available. To be more precise, it can be something like this:
<form id="registration_form" action="register">
<input id="username" type="text" onchange="checkAvailability();"/>
<div id="availability"></div>
</form>
<script type="text/javascript>
function checkAvailability()
{
$.ajax({
type: "GET",
url: "checkAvailability.php",
data: $("username").val(),
success: function(response) {
var status = $(response).find('status').text();
if (status == 'failed') $("#availability").html("This username is not available!");
else $("#availability").html("This username is available!");
},
dataType: "xml"
});
}
</script>
精彩评论