I'm using JQuery to call a php script which will add a record to the mySQL database.
This works fine for the first time I try to add something, but if I want to add more records to the database, it will not add anything. There are no errors in the console or php error log. It does not work if I refresh or reopen the page either.
jquery:
$(document).ready(function(){
$("#myForm").submit(function(){
var username = $("#username").val();
var password = $("#password").val();
var repassword = $("#repassword").val();
var email = $("#email").val();
var reemail = $("#reemail").val();
if(password != repassword)
{
alert("Passwords do not match");
return false;
}
else if(email != reemail)
{
alert("Emails do not match");
return false;
}
else {
$.post("signup_script.php",
{
username: username,
password: username,
email: email
});
}
});
});
php:
<?php
include_once('profile_Functions.php');
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
createUser($username,$password,$email);
?>
html:
<div class="body"></div>
<div class="grad"></div>
<div class="header">
<div>odd<span>job</span></div>
</div>
<br>
<div class="signup">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type = "text/javascript" src="js/js_functions.js"></script>
<form id ="myForm" action ="" method = "post" >
<input type="text" placeholder="username" id ="username" required = "required" maxlength = "15"><br>
<input type ="email" placeholder = "email" id = "email" required = "required" maxlength = "50"><br>
<input type ="email" placeholder = "re-enter email" id = "reemail" required = "required" maxlength = "50"><br>
<input type="password" placeholder="password" id="password" required = "required" pattern = "(?=.*\d)(?=.*[A-Z]).{10,}"><br>
<input type="password" placeholder="re-enter password" id ="repassword" required = "required"><br>
<p class = "passwordreq">Password must:</p>
<ol class = "passwordreq">
<li>Have 10 characters</li>
<li>Have one number</li>
<li>Have one uppercase letter</li>
</ol>
<input type="submit" value="sign up" id ="submit">
<input type="button" value="go back" onclick="window.location='index.html'">
</form>
insert function:
function setup(){
extract($_GET);
extract($_POST);
extract($_SERVER);
$host="localhost";
$user="root";
$passwd="";
$connect=mysql_connect($host,$user,$passwd) or die("error connecting mysql server");
mysql_select_db('oddjob',$connect) or die("error accessing db");
}
function createUser($name, $pass, $email){
setup();
$hashed_password = password_hash($pass, PASSWORD_DEFAULT);
$sql = "insert into profiles (UserName, Password, Email) values ('$name', '$hashed_password', '$email'); ";
$res = mysql_query($sql);
}
I wonder if the solution is related to this question: https://stackoverflow.com/a/6143475/652519.
Can you add the error function to your post function? Like so:
$.post("signup_script.php",
{
username: username,
password: username,
email: email
})
.error(function() { alert("error"); });
Then we can see if there are errors that happen upon insert in the DB.
You should close your connection each time
mysql_close($connect)
Related
<?php
include('connection.php');
$username = $_POST['user'];
$password = $_POST['pass'];
//to prevent from mysqli injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);
$sql = "select *from login where username = '$username' and password = '$password'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1){
echo "<h1><center> Login successful </center></h1>";
}
else{
echo "<h1> Login failed. Invalid username or password.</h1>";
}
?>
I have to do a website that works like google forms, for school. The thing is that in the signup form I get this error and I don t understand why I'm pretty new to the whole PHP stuff and I didn't find much about this error.
The HTML file
<html>
<head>
<title>PHP Signup system</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="frm">
<h1>Signup</h1>
<form name="f1" action="registration.php" onsubmit="return validation()" method="POST">
<p>
<label> UserName: </label>
<input type="text" id="user" name="Username" />
</p>
<p>
<label> Password: </label>
<input type="password" id="pass" name="Password" />
</p>
<p>
<label> Password: </label>
<input type="password" id="passc" name="Confirm Password" />
</p>
<p>
<label> Email: </label>
<input type="text" id="email" name="Email" />
</p>
<p>
<input type="submit" id="btn" value="Submit" />
</p>
</form>
</div>
<script>
function validation() {
var id = document.f1.user.value;
var ps = document.f1.pass.value;
var psc = document.f1.passc.value;
var em = document.f1.email.value;
if (id.length == "" && ps.length == "") {
alert("User Name and Password fields are empty");
return false;
} else {
if (id.length == "") {
alert("User Name is empty");
return false;
}
if (ps.length == "") {
alert("Password field is empty");
return false;
}
if (em.length == "") {
alert("Email field is empty");
return false;
}
if (ps != psc) {
alert("Passwords do not match");
return false;
}
}
}
</script>
</body>
</html>
It is pretty simple, and it doesn't have to look good, just to work.
EDIT: I got it, the problem was in fact that I misused the post method and names and that after that I forgot to make the connection with the database. credits to the guy in comments
Your post value is not set.
$_POST['foo'] // <== if not set or falsy, returns an undefined index warning
You must check if $_POST is populated before proceeding to execute you backend logic. Place the following at the top of your script and replace foo on your input's name.
if(!isset($_POST['foo']) || !$_POST['foo']){
// $_POST is not set. Notify user then exit!
echo 'Field "foo" is required!';
exit;
}
Or if your submit functions are in the same file of your form, try this:
if(isset($_POST['foo']) && $_POST['foo']){
// place your backend logic here to ensure that the required field(s) are field
}
I'm trying to make a change password modal. My problem is that if I want to update my password, it prints: "Incorrect username". How can I solve this problem? I'm using the password = PASSWORD method to hash the password. I'm trying to bind param with the $_SESSION["username"] but it didn't work.
index.php
<form name="resetform" action="changepass.php" id="resetform" class="passform" method="post" role="form">
<h3>Change Your Password</h3>
<br />
<input type="text" name="username" value="<?php echo $_SESSION["username"]; ?>" ></input>
<label>Enter Old Password</label>
<input type="password" class="form-control" name="old_password" id="old_password">
<label>Enter New Password</label>
<input type="password" class="form-control" name="new_password" id="new_password">
<label>Confirm New Password</label>
<input type="password" class="form-control" name="con_newpassword" id="con_newpassword" />
<br>
<input type="submit" class="btn btn-warning" name="password_change" id="submit_btn" value="Change Password" />
</form>
<!--display success/error message-->
<div id="message"></div>
<script>
$(document).ready(function() {
var frm = $('#resetform');
frm.submit(function(e){
e.preventDefault();
var formData = frm.serialize();
formData += '&' + $('#submit_btn').attr('name') + '=' + $('#submit_btn').attr('value');
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
success: function(data){
$('#message').html(data).delay(3000).fadeOut(3000);
},
error: function(jqXHR, textStatus, errorThrown) {
$('#message').html(textStatus).delay(2000).fadeOut(2000);
}
});
});
});
</script>
changepass.php
include_once 'include/connection.php';
if (isset($_POST['password_change'])) {
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['old_password']);
$newpassword = strip_tags($_POST['new_password']);
$confirmnewpassword = strip_tags($_POST['con_newpassword']);
// match username with the username in the database
$sql = "SELECT * FROM `user` WHERE `username` = ? AND password = PASSWORD(?)";
$query = $connect->prepare($sql);
$query->bindParam(1, $username, PDO::PARAM_STR);
$query->bindParam(2, $password, PDO::PARAM_STR);
if($query->execute() && $query->rowCount()){
$hash = $query->fetch();
if ($password == $hash['password']){
if($newpassword == $confirmnewpassword) {
$sql = "UPDATE `user` SET `password` = PASSWORD(?) WHERE `username` = ?";
$query = $connect->prepare($sql);
$query->bindParam(1, $newpassword, PDO::PARAM_STR);
$query->bindParam(2, $username, PDO::PARAM_STR);
if($query->execute()){
echo "Password Changed Successfully!";
}else{
echo "Password could not be updated";
}
} else {
echo "Passwords do not match!";
}
}else{
echo "Please type your current password accurately!";
}
}else{
echo "Incorrect username";
}
}
Your first major issue is your use of strip_tags, I'm not sure who told you to do that on input, but it's an incredibly bad practice. If you strip tags on password inputs, you're downgrading the security of any password that uses a <.
strip_tags('A<dsf$tgee!'); // a strong password of 'A<dsf$tgee!' becomes a weak password of 'A'.
This condition will also never evaluate to true:
$password == $hash['password']
Password is hashed via MySQL's PASSWORD() function so the plain text $password will never match the password column in MySQL.
I'm trying to add styling to certain parts of my form based on what happens in my PHP script. For example, I'd like to add a class to an input that the user fills out incorrectly that will trigger CSS rules, such as making the input's border red.
I thought I might be able to do this using jQuery at the end of my PHP script, but I haven't been successful despite writing it several different ways. I checked to make sure my new CSS styling came after the default styling too. It may also be worthwhile to mention that I'm using AJAX to validate as well, so the user stays on the registration page if the form is not filled out properly.
Here is my PHP script (jQuery is at the end):
<?php
if (isset($_POST['submit']))
{
include_once "_databaseHandler.php";
$username = mysqli_real_escape_string($connection, $_POST['username']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$confirmPassword = mysqli_real_escape_string($connection,
$_POST['confirmPassword']);
$errorEmpty = false;
//Check for empty fields
if (empty($username) || empty($email) || empty($password) ||
empty($confirmPassword))
{
echo "<span class='form-error'>Please fill in all fields</span>";
$errorEmpty = true;
}
else
{
$sqlUsername = "SELECT * FROM userinfo WHERE userName = '$username'";
$resultUsername = mysqli_query($connection, $sqlUsername);
$resultCheckUsername = mysqli_num_rows($resultUsername);
$sqlEmail = "SELECT * FROM userinfo WHERE userEmail = '$email'";
$resultEmail = mysqli_query($connection, $sqlEmail);
$resultCheckEmail = mysqli_num_rows($resultEmail);
//Check length of username
if (strlen($username) < 4)
{
echo "<span class='form-error'>Your username must be at least 4
characters long</span>";
$errorEmpty = true;
}
//Check if username is taken
else if ($resultCheckUsername > 0)
{
echo "<span class='form-error'>This username is already
taken</span>";
$errorEmpty = true;
}
//many other checks with exact same syntax using else if...
//Insert the user into the database
else
{
$sql = "INSERT INTO userinfo (userName, userEmail, userPassword) VALUES (?, ?, ?);";
$statement = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($statement, $sql))
{
echo "<span class='form-error'>Database error</span>";
exit();
}
else
{
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($statement, "sss", $username, $email, $hashedPassword);
mysqli_stmt_execute($statement);
$emailSubject = "wtf";
$emailMessage = "Hello my son";
mail($email, $emailSubject, $emailMessage);
session_start();
$_SESSION['register-success'] = 'You have successfully registered! Please verify your email before logging in.';
echo
"<script type=\"text/javascript\">
window.location.href='../index.php';
</script>";
exit();
}
}
}
}
else
{
header('Location: ../index.php');
exit();
}
?>
<reference path="jquery-3.3.1.min.js"/>
<script type="text/javascript">
var errorEmpty = "<?php echo $errorEmpty; ?>";
if (errorEmpty)
{
$("#register-username").addClass(".input-error");
}
</script>
Full context of related code:
jQuery:
/// <reference path="jquery-3.3.1.min.js" />
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var username = $("#register-username").val();
var email = $("#register-email").val();
var password = $("#register-password").val();
var confirmPassword = $("#register-confirm-password").val();
var submit = $("#register-submit").val();
$(".form-message").load("../shared/_registerAccount.php", {
username: username,
email: email,
password: password,
confirmPassword: confirmPassword,
submit: submit
});
});
});
HTML:
<?php
include "shared/_header.php";
?>
<div class="wrapper-register">
<div id="register-account">
<div class="register-title">
<h2>REGISTER ACCOUNT</h2>
</div>
<form action="shared/_registerAccount.php" method="post">
<div class="register-input">
<input id="register-username" type="text" name="username"
maxlength="16" placeholder="Username" />
</div>
<div class="register-input">
<input id="register-email" type="text" name="email"
maxlength="128" placeholder="Email" />
</div>
<div class="register-input">
<input id="register-password" type="password" name="password"
maxlength="128" placeholder="Password" />
</div>
<div class="register-input">
<input id="register-confirm-password" type="password"
name="confirmPassword" maxlength="128"
placeholder="Confirm Password" />
</div>
<input id="register-submit" type="submit" name="submit"
value="SIGN UP" class="register-button" />
</form>
<p class="form-message"></p>
</div>
</div>
<?php include "shared/_footer.php" ?>
<script src="javascript/register.js"></script>
</body>
</html>
There can be following issues when CSS is not being applied"
You have not included the CSS file (I don't see the file inclusion in your code)
You are applying it on an undefined ID or the class doesn't exist (Both of them can't be verified from your provided code).
The class name you are applying is wrong (In your case, you are applying '.input-error' if your class name starts with a '.', you need to escape it.)
I want to create form in HTML files. let say it calls index.html ( client will see this page), and the HTML will be included some ajax codes where it links to php (server connect to Mysql)
So that client can do (insert delete edit) to database by inserting form in the index.html. How possibly to do that?. Please give me a simple code so that I can learn. Thank you so much. I found that PHP can link to others php to retrieve the data. But I would love to use HTML instead ,to link to php on the server.
Thank you so much.
edited code
enter code here (this is index.html)
<html>
<head>
<title>Submit Form Using AJAX PHP and javascript</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="css/style.css" />
<script>
function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var contact = document.getElementById("contact").value;
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if (name == '' || email == '' || password == '' || contact == '')
{
alert("Please Fill All Fields");
}
else
{
//AJAX code to submit form.
$.ajax({
type: "POST",
url: "https://../test2.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}</script>
</head>
<body>
<div id="mainform">
<div class="innerdiv">
<h2>Submit Form</h2>
//div starts here
<form id="form">
<h3>Fill Your Information!</h3>
<div>
<label>Name :</label>
<br/>
<input type="text" id="name" /><br/>
<br/>
<label>Email :</label>
<br/>
<input type="text" id="email"/><br/>
<br/>
<label>Password :</label>
<br/>
<input type="password" id="password" /><br/>
<br/>
<label>Contact No :</label>
<br/>
<input type="text" id="contact" /><br/>
<br/>
<input type="button" id="submit" onclick="myFunction()" value="Submit"/>
</div>
</form>
<div id="clear"></div>
</div>
</body>
</html>
and this is the php.
//Fetching Values from URL
$name2 = $_POST['name1'];
$email2 = $_POST['email1'];
$password2 = $_POST['password1'];
$contact2 = $_POST['contact1'];
$servername = "localhost";
$username = "user";
$password = "userpwd";
$dbname = "dbname";
// Establishing connection with server..
$dbc = mysqli_connect($servername, $username, $password , $dbname)
or die('Error connecting to MySQL server.');
// Selecting Database
if (isset($_POST['name1'])) {
//Insert query
$query = mysqli_query("insert into form_element(name, email, password, contact) values ('$name2', '$email2', '$password2','$contact2')");
echo "Form Submitted succesfully";
}
//connection closed
mysqli_close($dbc);
?>
I don't get it work.
I don't have all the div's you had in there before, but you should be able to add them!
This should work once you put in the right username, password and database name in connection.php
If this doesn't work or isn't what you wanted, please let me know!
This is also up and running at http://emmetstudios.com/form, if you want to see it in operation.
Here's the code, (put it all in the same folder, different files):
connection.php:
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "yourusername";
$dbpass = "yourpassword";
$dbname = "yourdatabasename";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
success.php:
<?php
require 'connection.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
$contact = $conn->real_escape_string($_POST['contact']);
$query = "INSERT into form_element (name,email,password,contact) VALUES('" . $name . "','" . $email . "','" . $password . "','" . $contact . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo "Successful!";
$conn->close();
?>
index.php:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form" action="success" method="post" onsubmit="return validateForm()" name="upload">
Name:<br>
<input type="text" name="name"> <br><br>
Email:<br>
<input type="text" name="email"> <br><br>
Password:<br>
<input type="password" name="password"> <br><br>
Phone Number:<br>
<input type="text" name="contact"> <br><br>
<input id="submit" type="submit" value="Submit">
</form>
<script>
function validateForm() {
var name = document.forms["form"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["form"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
var password = document.forms["form"]["password"].value;
if (password == "") {
alert("Password must be filled out");
return false;
}
var contact = document.forms["form"]["contact"].value;
if (contact == "") {
alert("contact must be filled out");
return false;
}
}
</script>
</body>
</html>
I'm wondering if and how I could check if a username is being used.
I heard you can do this with jQuery but i just want something simple since I'm a beginner.
I have tried it but i can't seam to get it right. I just have it connected to a mysql database but since when a username with the same password as another account tries to logon, theres an issue, so i need this to stop people adding multiple usernames.
Here is my simple code for the registration form and the php
<form action="" method="POST">
<p><label>name : </label>
<input id="password" type="text" name="name" placeholder="name" /></p>
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email"/></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
</div>
<?php
require('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
$result = mysql_query($query);
if($result){
}
}
?>
For starters you don't want to just rely on something like unique field for doing this, of course you will want to add that attribute to your username column within your database but above that you want to have some sort of frontal protection above it and not rely on your database throwing an error upon INSERT INTO, you're also going to want to be using mysqli for all of this and not the old version, mysql. It's vulnerable to exploitation and no longer in common practice, here's what each of your files should look like:
connect.php
<?php
$conn = mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
register.php
<form action="insertuser.php" method="POST">
Username:
<input type="text" name="username" placeholder="Username" />
<br />
Password:
<input type="password" name="password" placeholder="Password" />
<br />
Name:
<input type="text" name="name" placeholder="Name" />
<br />
Email address:
<input type="text" name="email" placeholder="Email address" />
<br /><br />
<input type="submit" value="Register" />
</form>
<?php
// If there's an error
if (isset($_GET['error'])) {
$error = $_GET['error'];
if ($error == "usernametaken") {
echo "<h4>That username is taken!</h4>";
} elseif ($error == "inserterror") {
echo "<h4>Some kind of error occured with the insert!</h4>";
} else {
echo "<h4>An error occured!</h4>";
}
echo "<br />";
}
?>
Already have an account? Login here
insertuser.php
<?php
// Stop header errors
ob_start();
// Check if form has been posted
if (isset($_POST['username'])){
// Requre database connection file
require('connect.php');
// Clean the variables preventing SQL Injection attack
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
// Check if the username exists
// Construct SELECT query to do this
$sql = "SELECT id FROM user WHERE username = '".$username."';";
$result = mysqli_query($conn, $sql);
$rowsreturned = mysqli_num_rows($result);
// If the username already exists
if ($rowsreturned != 0) {
echo "Username exists, redirecting to register.php with an error GET variable!";
// Redirect user
header('Location: register.php?error=usernametaken');
} else {
// Construct the INSERT INTO query
$sql = "INSERT INTO user (username, password, email, name) VALUES ('".$username."', '".$password."', '".$email."', '".$username."');";
$result = mysqli_query($conn, $sql);
if($result){
// User was inserted
echo "User inserted!";
/* DO WHATEVER YOU WANT TO DO HERE */
} else {
// There was an error inserting
echo "Error inserting, redirecting to register.php with an error GET variable!";
// Redirect user
header('Location: register.php?error=inserterror');
}
}
}
?>
Good luck with whatever you're working on and I hope this helps!
James
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$query = "select username from user where username = '$username'";
$res = mysql_query($query);
$rows = mysqli_num_rows($res);
if ($rows > 0) {
print 'Username already exists...';
} else {
$query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
$result = mysql_query($query);
if($result){
}
}
}
Here is another example :) , succes.
<?php
//Set empty variables.
$usernameError = $emailError = $passwordError = $nameError = $okmsg = "";
$username = $password = $email = $name = "";
if (isset($_POST['submit'])) {
//Check if empty labels form
if (empty($_POST['name'])) {
$userError = "The 'name' is required.";
echo '<script>window.location="#registrer"</script>';
} else { $name = $_POST['name']; }
if (empty($_POST['email'])) {
$emailError = "El 'Email' es requerido.";
echo '<script>window.location="#registrer"</script>';
} else {
$email = $_POST['email'];
//Check only contain letters and whitespace.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "El 'Email' is not valid. ";
echo '<script>window.location="#registrer"</script>';
}
}
if (empty($_POST['password'])) {
$passwordError = "The 'password' is requiered.";
echo '<script>window.location="#registrer"</script>';
} else {
$password = $_POST['password'];
}
}
//Check if correctly filled
if ($name && $username && $email && $password) {
require('connect.php');
//Query SQL
$sql = "SELECT * FROM user WHERE username='$username'"; //String SQL
$query = mysqli_query($ConDB, $sql);//Query
//Securite
$username = mysqli_real_escape_string($ConDB, $username);
$password = mysqli_real_escape_string($ConDB, $username);
$passw = sha1($password);//For securite.
$name = mysqli_real_escape_string($ConDB, $username);
$email = mysqli_real_escape_string($ConDB, $username);
if ($existe = mysqli_fetch_object($query)) {
$usernameError = "The 'Username' is already exists.";
echo '<script>window.location="#registrer"</script>';
} else {
$sql = "INSERT INTO user (username, password, email, name) VALUES ('$username', '$passw', '$email', '$name')";
mysqli_query($ConDB, $sql);
$okmsg = "Register with succes.";
mysqli_close($ConDB);//Close conexion.
echo '<script>window.location="#registrer"</script>';
}
}
?>
<a name="registrer"></a>
<form action="" method="POST">
<p><label>name : </label>
<input id="password" type="text" name="name" placeholder="name" /></p>
<?php echo $nameError; ?>
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<?php echo $usernameError; ?>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email"/></p>
<?php echo $emailError; ?>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<?php echo $passwordError; ?>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
<?php echo $okmsg; ?>
</form>
--
-- DATA BASE: `user`
--
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE user (
id int(11) unsigned not null auto_increment primary key,
name varchar(50) not null,
email varchar(80) not null unique,
username varchar(30) not null unique,
password varchar(40) not null
)engine=InnoDB default charset=utf8 collate=utf8_general_ci;
You can try use jQuery AJAX for what you want.
First, add this to your registration.php file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// when user submit the form
$('form').on('submit', function(event){
$.ajax({
url: "check_username.php",
type: "POST",
dataType: "JSON",
data: {
username: $("#username").val() // get the value from username textbox
},
success: function(data){
if(data.status == "exists"){
alert('Username already existed');
}
else{
$('form').submit();
}
},
});
event.preventDefault();
});
</script>
So now your registration.php file will look like this
registration.php
<form action="" method="POST">
<p>
<label>name : </label>
<input id="password" type="text" name="name" placeholder="name" />
</p>
<p>
<label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" />
</p>
<p>
<label>E-Mail : </label>
<input id="password" type="email" name="email"/>
</p>
<p>
<label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" />
</p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// when user typing in 'username' textbox
$('form').on('submit', function(event){
$.ajax({
url: "check_username.php",
type: "POST",
dataType: "JSON",
data: {
username: $("#username").val() // get the value from username textbox
},
success: function(data){
if(data.status == "exists"){
alert('Username already existed');
}
else{
$('form').submit();
}
},
});
event.preventDefault();
});
</script>
Then create php file named check_username.php to check the username submitted by user if it is already existed in database or still available.
check_username.php
<?php
// Check if 'username' textbox is not empty
if(!empty($_POST['username'])){
$username = trim(mysqli_real_escape_string($_POST['username']));
// Check the database if the username exists
$query = "SELECT username FROM `user` WHERE username = '".$username."'";
$result = mysqli_query($query);
if(mysqli_num_rows($result) > 0){
// if username already exist
// insert into array, to be sent to registration.php later
$response['status'] = 'exists';
}
else{
// if username available
$response['status'] = 'available';
}
}
header('Content-type: application/json');
echo json_encode($response);
exit;
?>
Here is how it works:
1. When user click the register button, jQuery will call check_username.php.
2. Now in check_username.php it will check the database if the username submitted already exists or still available.
3. Whatever the result either exists or available, check_username.php will send the result back to registration.php as string contains 'exists' or 'available'.
4. registration.php now get the result and will check the result sent by check_username.php if it contain 'exists' or 'available'. If the string is 'exists' then alert will be triggered. If the string is 'available', the form will be submitted.