PHP form validation with javascript alert box - php

Hi i am new to PHP and i am trying to submit a registration form and it works fine but the problem is that when it gives some error like username already exists or password too short in an alert box and then it reloads the form page again and the user has to fill the whole form again i want the fields that are correct to remain unchanged
here is the form page code
<!DOCTYPE HTML>
<html>
<head>
<title>Details</title>
<link rel="stylesheet" type="text/css" href="reg.css">
</head>
<body id="body">
<div id="mmw"> <span> MAP MY WAY </span></div>
<form name="reg" id="reg" method="post" action="insert.php">
<h2>Kindly fill up your Information</h2>
<p>
<input name="username" required class="name" placeholder="Type Your User name" />
<input name="password" placeholder="Type Your Password" class="name" type="password" required />
<input name="first_name" required class="name" placeholder="Type Your First name" />
<input name="last_name" required class="name" placeholder="Type Your Last name" />
<input name="email" required class="email" placeholder="Type a valid E-Mail address" />
<input name="m_no" class="name" placeholder="Type Your Mobile #"/>
<input name="v_name" required class="name" placeholder="Type Your Vahical model and name"/>
<input name="capacity" required class="name" placeholder="Seating capacity"/>
<input name="fuel_type" required class="name" placeholder="Runs on what fuel type"/>
</p>
<p>
<input name="submit" class="btn" type="submit" value="Register" />
</p>
</form>
</div>
</body>
</html>
and here is the page that is processing the data
<?php
$con = mysqli_connect("localhost", "root", "", "map_my_way");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$first_name = mysqli_real_escape_string($con, $_POST['first_name']);
$last_name = mysqli_real_escape_string($con, $_POST['last_name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$m_no = mysqli_real_escape_string($con, $_POST['m_no']);
$v_name = mysqli_real_escape_string($con, $_POST['v_name']);
$fuel_type = mysqli_real_escape_string($con, $_POST['fuel_type']);
$capacity = mysqli_real_escape_string($con, $_POST['capacity']);
$exists = mysqli_num_rows(mysqli_query($con,"SELECT * FROM members WHERE username='" . $username . "'"));
if ($exists > 0) {
echo "<script language=\"JavaScript\">\n";
echo "alert('username already exists!');\n";
echo "window.location='reg.php'";
echo "</script>";
}
if (strlen ($password) < 6){
echo "<script language=\"JavaScript\">\n";
echo "alert('password must be 6 characters');\n";
echo "window.location='reg.php'";
echo "</script>";
}
else{
// if ($password < 6) {
// echo "<script language=\"JavaScript\">\n";
// echo "alert('username already exists!');\n";
// echo "window.location='reg.php'";
// echo "</script>";
// } else{
//insert query
$sql = "INSERT INTO members (username, password, first_name, last_name, email, m_no, v_name, fuel_type, capacity)
VALUES ('$username', '$password', '$first_name', '$last_name', '$email', '$m_no', '$v_name', '$fuel_type', '$capacity')";
}
//}
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
else{
header("location:pic.php");
}
// Register $username
session_start();
$_SESSION['login'] = true;
$_SESSION['username'] = $username;
mysqli_close($con);
?>
Thanks in advance

header('Location: http://example.com/some/url'); relplace it with the javascript
also try to make a function to the escape string less typing:
function security($danger) {
mysqli_real_escape_string($con, $danger)}
simply call it with the username like $username = security($_POST['username'])

Related

Unable to retrieve data from DB and using $_SESSION variable

I've been working on a project that has to do with renting houses. Visitors can register or log-in, and only logged-in users can Add a house for rental. Each user has his own profile showing his username, email and accommodations he has uploaded for rental.
My problem is that I cannot retrieve the email of the logged in user. Also, on my MySQL DB I'm using a foreign key in my accom(modation) table, which references the primary key(USER-ID) of the users. The key fails to match the USER-ID.
Any advice would be really helpful. Thank you a lot in advance.
Posting some of the code below:
register.php
<?php include('server.php') ?>
<? php
if (isset($_SESSION['username'])) {
$_SESSION['msg'] = "You're now logged in.";
unset($_SESSION["register.php"];
header('Location: user_index.php');
}
?>
<!DOCTYPE html>
<html>
<link href="https://fonts.googleapis.com/css?family=Eater" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="mystyle.css">
<body>
<p id="pagetitle">Booking Planet </p>
<div class="navbar" id="topnav">
<button onclick="document.getElementById('id01').style.display='block'"
style="width:auto;">Login</button>
<button onclick="document.getElementById('id02').style.display='block'"
style="width:auto;">Register</button>
HOME
</div>
<?php
$db = mysqli_connect('localhost', 'root', '', 'registration');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($db,"SELECT * FROM accom");
echo "<p> </p>";
echo "<div class='acclist'> Explore some fairytale destinations.. </div>";
echo "<ul>";
while($row = mysqli_fetch_array($result))
{
$image=$row['image'];
$target = "images/".basename($image);
echo "<img src='" . $target . "' width=800 height=500/>";
echo "<li id='title'><b>" . $row['title'] . "</b></li>";
echo "<li> Description: <i>" . $row['description'] . "</i></li>";
echo "<li> Address: <i>". $row['address'] . "</i></li>";
echo "<li> Available from: <i>" . $row['checkin'] . "</i></li>";
echo "<li> Available until: <i>" . $row['checkout'] . "</i></li>";
?><button onclick="document.getElementById('id01').style.display='block'"
type='button' class='bookbtn'>Log-in to book now!</button>
<?php
echo "<li><img src='sepline.png' width=1500 height=75> </li>";}
echo "</ul>";
mysqli_close($db);
?>
</div>
<div id="id01" class="modal">
<? php include('errors.php'); ?>
<form action="" method="post" class="modal-content animate" name="login" >
<div class="logocontainer"> Booking Planet
</div>
<h3> Account Log-in. </h3>
<div class="container">
<? php echo $errors; ?>
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password"
required>
<button type="submit" name="login_user">Login</button>
</div>
<div class="container">
<button type="button" class="cancelbtn" id="cncl1">Cancel</button>
</div>
</form>
</div>
<!-- REGISTRATION -->
<div id="id02" class="modal">
<form action="" method="post" class="modal-content animate" name="register"
>
<div class="logocontainer"> Booking Planet
</div>
<h3> Create an account. </h3>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Name</b></label>
<input type="text" placeholder="Enter your Name!" name="name" required>
<label><b>Surname</b></label>
<input type="text" placeholder="Enter your Surname!" name="surname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<label><b>Email</b></label>
<input type="email" placeholder="Enter Email" name="email" required>
<div class="avatar"><label>Select your avatar: </label>
<input type="file" name="avatar" accept="image/*" required />
<button type="submit" name="reg_user">Register</button>
</div>
<div class="container">
<button type="button" class="cancelbtn" id="cncl2">Cancel</button>
</div>
</form>
</div>
<script src="myscripts.js"></script>
</body>
</html>
user_index.php: is pretty much similar to register.php, it's where people who have registered or logged-in are redirected. I'm posting the beginning of the code.
<?php include('server.php'); ?>
<?phpinclude('auth.php');
session_start();
if ($_SESSION['username']<1) {
session_destroy();
unset($_SESSION['username']);
header("Location: register.php");
}
$db = mysqli_connect('localhost', 'root', '', 'registration');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($db,"SELECT email FROM users WHERE
username='$_SESSION['username']'");
$row = mysqli_fetch_array($result);
$_SESSION['email'] = $result;
$username = $_SESSION['username'];
$_SESSION['id']=$id;
header("Location: server.php");
?>
server.php: contains the validation for registration and logging-in. Also, links to the DB. I will be skipping the validation parts.
<?php
session_start();
$email=$_SESSION['email'];
// initializing variables
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');
//...validationon code
//once no errors, register user
if (count($errors) == 0) {
$password = md5($password);//encrypt the password before saving in the
database
$query = "INSERT INTO users (username, email, password, name, surname)
VALUES('$username', '$email', '$password', '$name', '$surname')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in";
header('Location: user_index.php');
}
}
// LOGIN USER
$msg = '';
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND
password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
session_start();
$_SESSION['email']=$row['email'];
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['id']= $id;
$_SESSION['success'] = "You are now logged in";
header('Location: user_index.php');
}else {
echo $msg;
}
}
}
auth.php
<?php
session_start();
if(!isset($_SESSION["username"])){
echo $errors; }
?>
For any additional information you might need, please feel free to ask anything.
I am genuinely sorry for the block of text and code.

Display the result of a registration page on top of the registration form

I know little about coding.
This is relating to a registration form i am creating. I have created the form. It is adding the form to database. But it want it to be displaying the result, for example - 'Passwords not matching, please try again' on top of the form. How to get that?
Thanks in advance
Here my code:
<?php
$conn = mysqli_connect("localhost","root","");
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysqli_select_db($conn, 'registration');
if(isset($_POST['submitbutton'])){
if ($_POST['password'] == $_POST['confirm_password']) {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$firm = mysqli_real_escape_string($conn, $_POST['firm']);
$check_email_exists = mysqli_query($conn, "SELECT email FROM users WHERE email = '$email'");
$count = mysqli_num_rows($check_email_exists);
if ($count == 0) {
$sql = "INSERT INTO users(email, password, gender, fname, lname, firm) VALUES('$email', '$password', '$gender', '$fname', '$lname', '$firm')";
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
// close connection
mysqli_close($conn);
} else {
die('Email exists, Please use a different email');
}
}
else {
die('Passwords not matching, please try again');
}
}
and here my html
<div class="registration-container">
<div class="registrationpage-heading">
<h2>Kostenlos und ohne Installation testen</h2>
<p>Nutzen Sie den kostenlosen Funktionumfang von bmgenerator zeitlich uneingeschränkt. Weder Bankdaten noch Kreditkarte notwendig.</p>
</div>
<div class="user-login">
<form class="login-form" action="user_login.php" method="post">
<input required type="email" name="email" id="user_email" style="color:#888" size="35" value="E-mail"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<input required type="password" name="password" id="user_password" style="color:#888" size="35" placeholder="Passwort"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<input required type="password" name="confirm_password" id="user_confirm_password" style="color:#888" size="35" placeholder="Passwort wiederholen"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<select name="gender">
<option>Herr</option>
<option>Frau </option>
</select><br><br>
<input required type="text" name="fname" id="user_firstname" style="color:#888" size="35" placeholder="Vorname"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<input required type="text" name="lname" id="user_lastname" style="color:#888" size="35" placeholder="Nachname"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<input required type="text" name="firm" id="user_companyname" style="color:#888" size="35" placeholder="Firmenname"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<input type="submit" name="submitbutton" id="submit" value="Kostenlos registrieren">
</form>
</div>
<div class="register-terms">
<p>Mit der Registrierung stimmen Sie den Datenschutzbestimmungen und den AGB zu.</p>
</div>
</div>
First of all it is not recommended to place the form and the processor page on the same page to void redundant insert via refresh. However, in the processor section you have to use any mean of redirect after any end of the process, in your code die() and echo should be replaced with the redirect with a parameter of pre specified message. for instance, you have four ends in your processor, so your code should look like:
<?php
$conn = mysqli_connect("localhost","root","");
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysqli_select_db($conn, 'registration');
if(isset($_POST['submitbutton'])){
if ($_POST['password'] == $_POST['confirm_password']) {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$firm = mysqli_real_escape_string($conn, $_POST['firm']);
$check_email_exists = mysqli_query($conn, "SELECT email FROM users WHERE email = '$email'");
$count = mysqli_num_rows($check_email_exists);
if ($count == 0) {
$sql = "INSERT INTO users(email, password, gender, fname, lname, firm) VALUES('$email', '$password', '$gender', '$fname', '$lname', '$firm')";
if(mysqli_query($conn, $sql)){
header("Location: user_login.php?msg=1");
exit();
} else{
header("Location: user_login.php?msg=2");
exit();
}
// close connection
mysqli_close($conn);
} else {
header("Location: user_login.php?msg=3");
exit();
}
}
else {
header("Location: user_login.php?msg=4");
exit();
}
}
$msg = [
"Records added successfully.",
"SQL Error",
"Email exists, Please use a different email",
"Passwords not matching, please try again"
];
if (isset($_GET['msg']) && isset($msg[($_GET['msg']-1)])){
$message = $msg[($_GET['msg']-1)];
}
// In your form
....
</div>
<?php if (isset($message)): ?>
<div class="message"><?=$message;?></div>
<?php endif; ?>
<div class="user-login">
<form class="login-form....
In above scenario, submit the form page itself using
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
But make registration html to php file
<?php
if(isset($_POST['submitbutton'])){
//perform validation, display error if any
}
?>
If you want to go modular approach then use class having validate, register method after submit include class file and use methods
For each error message make a variable $message="Password not matching..." and then after <div class="user-login"> you can put:
<?php echo "<p>$message</p>"; ?>
Remember to create a blank $message="".
Hope it helps.

Why does my Register form still not input data into my MySQL tables

I'm trying to link a register page with my login page to allow new users to register an account to use on my application. I've linked the form up to my tbl_Users table on MySQL in which holds all the information that the users would input into this form. I've properly set everything up using queries and such and the form displays properly at the very least. However when I click submit, the page just refreshed with the fields now empty again and no new data within my table on the database. Where am I going wrong? (Extra-note: I'm still in the process of coding in the safety code to prevent sql-injections)
ConnectorCode.php
<?php
$conn = mysqli_connect("localhost", "b4014107", "Win1", "b4014107_db2") or die (mysqli_connect_error());
?>
Register.php
<?
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include('ConnectorCode.php');
if(isset($_POST['submit'])) {
$FName = $_POST['First_Name'];
$LName = $_POST['Last_Name'];
$Email = $_POST['Email'];
$UName = $_POST['User_Name'];
$Password = $_POST['Password'];
$FName = mysqli_real_escape_string($conn, $FName);
$LName = mysqli_real_escape_string($conn, $LName);
$Email = mysqli_real_escape_string($conn, $Email);
$UName = mysqli_real_escape_string($conn, $UName);
$Password = mysqli_real_escape_string($conn, $Password);
$sql = "SELECT Email FROM tbl_Users WHERE Email='$Email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
echo "Sorry, the email you are trying to enter already exists";
}
else
{
$query = mysqli_query($conn, "INSERT INTO tbl_Users(First_Name, Last_Name, Email, User_Name, Password) VALUES ('$FName', '$LName', '$Email', '$UName', '$Password')");
if($query)
{
echo "Thank you for registering";
}
header('Location: Index.php');
}
}
?>
<!DOCTYPE HTML>
<head>
<title>Register</title>
</head>
<body>
<h1> Register Page </h1>
<p> Please fill in the form to register <p>
<form method="post" action="">
<fieldset>
First Name: <br />
<input name="First_Name" type="text" class="input" size="25" required /> <br /> <br />
Last Name: <br />
<input name="Last_Name" type="text" class="input" size="25" required /> <br /> <br />
Email: <br />
<input name="Email" type="email" class="input" size="25" required /> <br /> <br />
Username: <br />
<input name="User_Name" type="text" class="input" size"25" required /> <br /> <br />
Password: <br />
<input name="Password" type="password" class="input" size="25" required /> <br /> <br/>
<input type="submit" name="submit" value="Register!" />
</fieldset>
</form>
</body>
</html>
You do not meet the condition isset($_POST['VALUES']) because you don't have field with name="VALUES".
Change
if(isset($_POST['VALUES'])) {
to
if(isset($_POST['submit'])) {
You had a lot missing...
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once 'ConnectorCode.php';
if(isset($_POST['submit']))
{
$FName = mysqli_real_escape_string($conn, $_POST['First_Name']);
$LName = mysqli_real_escape_string($conn, $_POST['Last_Name']);
$Email = mysqli_real_escape_string($conn, $_POST['Email']);
$UName = mysqli_real_escape_string($conn, $_POST['User_Name']);
$Password = mysqli_real_escape_string($conn, $_POST['Password']); // why did you need to repeat this all twice?
$sql = "SELECT * FROM tbl_Users WHERE Email='$Email'"; // ? didn't understand why you was asking for the Email using the Email...
$result = $conn->query($sql);
if(count($result) == 0)
{
$insert_sql = "INSERT INTO tbl_Users (First_Name,Last_Name,Email,User_Name,Password) VALUES ('$FName','$LName','$Email','$UName','$Password')";
if($conn->query($insert_sql)) // You forgot to query this
{
echo "Thank you for registering";
header('Location: index.php'); // lowercase i
exit; // you forgot this
}
}
else
{
echo "Sorry, that email already exists!";
}
$conn->close(); // you forgot this
}
?>
Hope this helps...

Check if username is being used

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.

PHP not writing data in MYSQL

This is a school project and this particular page is to register a new user it does not display errors but it does not fill the MYSQL data base the connection for the database is in another page and I used the require function functions.php is where I am writing the connection function please help :(
<?php
include_once("menu.php");
?>
<form action="login.php" method="POST">
<?php
if ((isset($_POST['username']))&& (isset($_POST['password'])) && (isset($_POST['password2'])) && (isset($_POST['email'])))
{
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$email = $_POST['email'];
if ($password == $password2)
{
require_once("functions.php");
$connection = connectToMySQL();
$Query = "SELECT count(*) FROM tbl_users WHERE username='$username'";
$Result = mysqli_query($connection,$Query)
or die("Error in the query :". mysqli_error($connection));
$row = mysqli_fetch_row($Result);
$counter = $row[0];
if ($counter > 0)
{
echo "Username alredy exsist with the movie assosiation website<br/>";
echo "<input type=\"submit\" class=\"button\" value=\"Back\"/>";
}
else
{
$insertQuery = "INSERT INTO 'tbl_users'(username,password,email,role) VALUES ('$username',sha1('$password'),'$email','registered')";
$insertResult = mysqli_query($connection,$insertQuery)
or die("Error in the query :". mysqli_error($connection));
echo "account created !! <br />";
echo "<input type=\"button\" class=\"button\" value=\"Log In\" onclick=\"location.href='login.php'\"> ";
}
}
}
else
{
?>
<label>
<span>Username:</span>
<input id="username" type="text" name="username" placeholder="enter your Username" required />
</label></br>
<label>
<span>Password</span>
<input id="password" type="password" name="password" placeholder="enter your Password" required />
</label></br>
<label>
<span>Re-Enter Password</span>
<input id="password2" type="password" name="password2" placeholder="re-enter your Password" required />
</label></br>
<label>
<span>Email</span>
<input id="email" type="email" name="email" placeholder="enter email" required />
</label></br>
<label>
<span> </span>
<input id="submit" class="button" type="submit" name="submit" value="Submit"/>
</label>
</form>
<?php
}
?>
<?php
require_once("footer.php")
?>
remove single quote from your table name
try this
$insertQuery = "INSERT INTO `tbl_users`(username,password,email,role) VALUES ('$username',sha1('$password'),'$email','registered')";
instead of
$insertQuery = "INSERT INTO 'tbl_users'(username,password,email,role) VALUES ('$username',sha1('$password'),'$email','registered')";
Error in your sql statement.
Try this.
$insertQuery = "INSERT INTO tbl_users (username,password,email,role) VALUES ('{$username}',sha1('{$password}'),'{$email}','registered')";
or this
$insertQuery = "INSERT INTO tbl_users (username,password,email,role) VALUES ('".$username."',sha1('".$password."'),'".$email."','registered')";

Categories