I am new to PHP and i am trying to built a registration form for users and to saved user input to database, but user data are not saving to database. Someone please help !
cofiguration.php
<?php
define('HOST','localhost');
define('USER','root');
define('PASSWORD_HOST','');
define('DATABASE','test_db');
if (defined('HOST') && defined('USER') && defined('PASSWORD_HOST') && defined('DATABASE')){
$conn=mysqli_connect(HOST,USER,PASSWORD_HOST,DATABASE);
}else{
die("connection failed:" .mysqli_connect_error());
}
?>
here i am updating my whole index.php file.
index.php
<!DOCTYPE html>
<html>
<style>
.error {color: #FF0000;}
</style>
<?php
require_once "configuration.php";
//set trigger for login form
$registereduserValidInput=true;
if (isset($_POST['RegisterSubmitButton']))
{
//if firstname field is empty
if (empty($_POST["firstname"]))
{
$firstnameErr="Let us know your first name";
$registereduserValidInput=false;
}else
{
$firstname = test_input($_POST["firstname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{
$firstnameErr1="please provide letters only";
$registereduserValidInput=false;
}
}
/*.................................................................................................
...................................................................................................*/
//if last name field is empty
if (empty($_POST["lastname"]))
{
$lastnameErr="Please provide last name";
$registereduserValidInput=false;
}else
{
$lastname=test_input($_POST["lastname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$lastname))
{
$lastnameErr1="Please provide letters only";
$registereduserValidInput=false;
}
}
/*.................................................................................................
...................................................................................................*/
//check email field
if (empty($_POST["useremail"]))
{
$emailErrA = "Email is required";
$registereduserValidInput = false;
}else
{
$email = test_input($_POST["useremail"]);
//email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr1A = "Invalid email format";
}
}
/*.................................................................................................
...................................................................................................*/
//check password field
if(empty($_POST["userpassword"]))
{
$passwordErr="Password is required";
$registereduserValidInput = false;
}else {
$password = test_input($_POST["userpassword"]);
}
/*.................................................................................................
...................................................................................................*/
//password verification field
if(empty($_POST["verifypassword"]))
{
$verifypasswordErr="Re-enter your Password";
$registereduserValidInput = false;
}else {
$verifypassword = test_input($_POST["verifypassword"]);
}
/*.................................................................................................
...................................................................................................*/
//script to check whether the two password fields matches or not
if (strcmp($password, $verifypassword) !== 0)
{
$passwordnotmatch="Password do no match"; //if passwords do not match generate error to user
$registereduserValidInput = false;
}else {
$passwordmatch="password match";
}
/*.................................................................................................
...................................................................................................*/
/*.................................................................................................
...................................................................................................*/
// if all inputs are provided by user run sql query to check whether email is already registered or not
if($registereduserValidInput==true){
$sql1=mysqli_query($conn, "SELECT * FROM registereduser WHERE useremail='$_POST[email]'");
$rows1 = mysqli_num_rows($sql1);
if($rows1==0)
{
//insert user input to "registeredUser" table
$sqlTable ="INSERT INTO registereduser (firstname, lastname, useremail, userpassword) VALUES ('".$firstname."', '".$lastname."', '".$email."','".$password."')";
mysqli_query($conn, $sqlTable);
}else{
echo "This email ID is already registered with us. kindly login again!";
die;
}
}
}
?>
<body>
<form method="post" action="index.php">
<h2>Registration Form</h2><br><br>
Enter Your First Nmae:<br><br>
<input type="text" name="firstname" placeholder="First Name" value="">
<span class="error"> <?php echo $firstnameErr; ?> </span>
<span class="error"> <?php echo $firstnameErr1; ?> </span><br><br>
Enter Your Last Name:<br><br>
<input type="text" name="lastname" placeholder="Last Name" value="">
<span class="error"> <?php echo $lastnameErr; ?> </span>
<span class="error"> <?php echo $lastnameErr1; ?> </span><br><br>
Enter Your Email:<br><br>
<input type="text" name="useremail" value="" >
<span class="error"> <?php echo $emailErrA;?></span>
<span class="error"> <?php echo $emailErr1A;?></span><br><br>
Enter Your Password:<br><br>
<input type="password" name="userpassword" value="">
<span class="error"> <?php echo $passwordErr;?></span><br><br>
Re-enter Your Password:<br><br>
<input type="password" name="verifypassword" value="">
<span class="error"> <?php echo $verifypasswordErr;?></span>
<span class="error"> <?php echo $passwordmatch;?></span><br><br>
<input type="submit" name="RegisterSubmitButton" value="Click here to Register">
</form>
</body>
</html>
The code to perform the database query and insert should be:
if($registereduserValidInput==true){
$sql1=mysqli_query($conn, "SELECT * FROM registereduser WHERE useremail='$_POST[email]'") or die(mysqli_error($conn));
$rows1 = mysqli_num_rows($sql1);
if($rows1==0)
{
//insert user input to "registeredUser" table
$sqlTable ="INSERT INTO registereduser (firstname, lastname, useremail,userpassword) VALUES ('".$firstname."', '".$lastname."', '".$email."','".$password."')";
mysqli_query($conn, $sqlTable) or die(mysqli_error($conn));
}else{
echo "This email ID is already registered with us. kindly login again!";
die;
}
}
You were missing the $conn argument in the SELECT query (you had the variable at the end of the SQL instead), and you never called mysqli_query() on $sqlTable.
You should also look up how to use prepared statements and bind_param. Substituting variables into a query leaves you open to SQL injection.
Few error I have found..
No field for password in Form or any variable for $password.
Not getting any method name test_input
$sql1=mysqli_query("SELECT * FROM registereduser WHERE useremail='$_POST[email]',$conn");
should be like
$sql1=mysqli_query($conn, "SELECT * FROM mdm_users WHERE school_name='$_POST[useremail]'");
and Most
$sqlTable ="INSERT INTO 'registereduser' ('firstname', 'lastname', 'useremail','userpassword') VALUES ('".$firstname."', '".$lastname."', '".$email."','".$password."')";
line should be like
$sqlTable ="INSERT INTO registereduser (firstname, lastname, useremail,userpassword) VALUES ('".$firstname."', '".$lastname."', '".$email."','".$password."')";
mysqli_query($conn, $sqlTable);
please remove the single quotes in table and column names.
Related
Although everything looks fine in my program (e.g. register2.php), I have some syntax and binding issues. As it keeps throwing the error on line 73 even though the data successfully entered my database named "webprojadmin", and the table named "users".
here is my connected PDO database:
<?php
session_start();
$host = "127.0.0.1:3308";
$username = "root";
$password = "root";
$dbname = "webprojadmin";
$dsn = "mysql:host=$host;dbname=$dbname";
$optionen = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
// Create connection
$cxn = new PDO($dsn, $username, $password, $optionen);
// set the PDO error mode to exception
$cxn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Success: A proper connection to MySQL was made! The"." ".$dbname." "."database is great." . PHP_EOL;
//echo "Host URL: " . $host . PHP_EOL;
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
And here is my program, register2.php
<?php
require "dbcxn.php";
?>
<center>
<div>
<h1>Add a new web user account</h1>
<form action="" method="post">
<p>Full Name:<input type="text" name="fullname" placeholder="enter your full name"></p>
<p>Email:<input type="text" name="email" placeholder="enter your email address"></p>
<p>Password:<input type="password" name="pass" placeholder="enter passowrd"></p>
<p>Type<select name="utype">
<option value="FA">Academic, Faculty & Staff</option>
<option value="UG">Undergraduate Student</option>
<option value="PG">Postgraduate Student</option>
<option value="AU">Undergraduate Alumni</option>
<option value="AP">Postgraduate Alumni</option>
</select><p>
<p>Bio:<br><textarea id="textboxid" type="text" name="bio" placeholder="May you introduce to us, briefly?"></textarea></p>
<p>Awards:<br><textarea id="textboxid" type="text" name="awards" placeholder="Have you received any awards? If yes, what are they?"></textarea></p>
<p>Publications:<br><textarea id="textboxid" type="text" name="pub" placeholder="Have you published any written works? If yes, what are they?"></textarea></p>
<p>Thesis Topic:<br><textarea id="textboxid" type="text" name="ttopic" placeholder="What is the title of the Thesis you are doing/about to do/recently done?"></textarea></p>
<p>Thesis abstract:<br><textarea id="textboxid" type="text" name="tabstract" placeholder="If you have told the thesis topic, what is it about? Tell us briefly. If not, leave it blank."></textarea></p>
<p><input type="submit" name="btn_register" value="Create an account"/></p>
</form>
</div>
</center>
<?php
if (isset($_POST["btn_register"])) //button name "btn_register"
{
$fullname = strip_tags($_POST["fullname"]);
$email = $_POST["email"];
$pass = $_POST["pass"];
$utype = $_POST["utype"];
$bio = $_POST["bio"];
$awards = $_POST["awards"];
$pub = $_POST["pub"];
$ttopic = $_POST["ttopic"];
$tabstract = $_POST["tabstract"];
$sql = "INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES ('$fullname', '$email', '$pass', '$utype', '$bio', '$awards', '$pub', '$ttopic', '$tabstract')";
echo ("<pre>\n".$sql."\n</pre>\n");
if(empty($fullname)) {
$errorMsg[]="Please enter username"; //check username textbox not empty
}
else if(empty($email)) {
$errorMsg[]="Please enter email"; //check email textbox not empty
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorMsg[]="Please enter a valid email address"; //check proper email format
}
else if(empty($pass)) {
$errorMsg[]="Please enter password"; //check passowrd textbox not empty
}
else if(strlen($pass) < 6) {
$errorMsg[] = "Password must be atleast 6 characters"; //check passowrd must be 6 characters
}
else
{
try
{
$select_stmt=$cxn->prepare("SELECT fullname, email FROM users
WHERE fullname=:ufname OR email=:uemail"); // sql select query
$select_stmt->execute(array(':ufname'=>$fullname, ':uemail'=>$email)); //execute query
$row=$select_stmt->fetch(PDO::FETCH_ASSOC);
if($row["fullname"]==$fullname){
$errorMsg[]="Sorry username already exists"; //check condition username already exists
}
else if($row["email"]==$email){
$errorMsg[]="Sorry email already exists"; //check condition email already exists
}
else if(!isset($errorMsg)) //check no "$errorMsg" show then continue
{
$new_pass = password_hash($pass, PASSWORD_DEFAULT); //encrypt password using password_hash()
$query = "INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES ('$fullname', '$email', '$pass', '$utype', '$bio', '$awards', '$pub', '$ttopic', '$tabstract')";
//$query2 = $sql;
//$query2run = $cxn->prepare($query2);
//$query2exec = $query2run->execute();
//$row=$query2run->fetch(PDO::FETCH_ASSOC);
$insert_stmt=$cxn->prepare("INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES (:ufname,:uemail,:upass,:uutype,:ubio,:uawards,:upub,:uttopic,:utabstract)"); //sql insert query
if ($insert_stmt->execute(array( ':ufname' =>$fullname,
':uemail'=>$email,
':upass'=>$new_pass,
':uutype'=>$utype,
':upass'=>$bio,
':upass'=>$awards,
':upass'=>$pub,
':upass'=>$ttopic,
':upass'=>$tabstract))) {
$registerMsg = "Register Successfully..... Please Click On Login Account Link"; //execute query success message
header("refresh:1; index.php");
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
if(isset($errorMsg))
{
foreach($errorMsg as $error)
{
?>
<div>
<strong>WRONG ! <?php echo $error; ?></strong>
</div>
<?php
}
}
if(isset($registerMsg))
{
?>
<div>
<strong><?php echo $registerMsg; ?></strong>
</div>
<?php
}
?>
</section>
I created a registration.php a login user.php an error.php and a server.php which errors validate and server connects my php form to database. login.php is working as is saying wrong id and/or password while registration form not working. When I click submit its just like refreshing and nothing its saved to database. Trying 3 days and can't figure why. maybe its my p.c problem? I'm working with XAMPP and phpmyadmin and dreamweaver.
here is my register.php.
<?php include('server.php') ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Registration Form</title>
<link rel="stylesheet" type="text/css" href="forms.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<?php include('errors.php'); ?>
<div class="input-group">
<label>Name:</label>
<input type="text" name="name">
</div>
<div class="input-group">
<label>Surname:</label>
<input type="text" name="surname">
</div>
<div class="input-group">
<label>Password:</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm Paswword:</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<label>Student ID:</label>
<input type="text" name="studentid">
</div>
<div class="input-group">
<label>Email:</label>
<input type="text" name="email">
</div>
<div class="input-group">
<label>Course:</label>
<input type="text" name="course">
</div>
<div class="input-group">
<center><button type="submit" name="register" class="btn">Register</button></center>
</div>
<p>
Already a registered student? Sign in
</p>
</form>
</body>
</html>
and this is my server.php
<?php
session_start();
// variable declaration
$name = "";
$surname = "";
$email = "";
$studentid = "";
$password_1 ="";
$password_2 = "";
$course = "";
$errors = array();
$_SESSION['success'] = "";
// connect to database
$db = mysqli_connect('localhost', 'root', '', 'registration');
// if register button clicked receive all inputs from the form
if (isset($_POST['reg_user'])) {
$name = mysqli_real_escape_string($db, $_POST['name']);
$surname = mysqli_real_escape_string($db, $_POST['surname']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$studentid = mysqli_real_escape_string($db, $_POST['studentid']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_1 = md5($password_1);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
$password_2 = md5($password_2);
$course = mysqli_real_escape_string($db, $_POST['course']);
// ensure that form fields are filled properly
if (empty($name)) {
array_push($errors, "Name is required");
}
if (empty($surname)) {
array_push($errors, "Surame is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($studentid)) {
array_push($errors, "Student ID is required");
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}
if (empty($course)) {
array_push($errors, "Course is required");
}
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
if (count($errors) == 0) {
$password = md5($password_1); //encrypt the password before saving in the database
$query = "INSERT INTO users (id, name, surname, email, studentid, password, course)
VALUES(0,'$name','$surname', '$email', '$studentid' '$password', '$course')";
mysqli_query($db, $query);
$_SESSION['studentid'] = $studentid;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
// login user
if (isset($_POST['login_user'])) {
$studentid = mysqli_real_escape_string($db, $_POST['studentid']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($studentid)) {
array_push($errors, "Student ID is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE studentid='$studentid' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['studentid'] = $studentid;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}else {
array_push($errors, "Wrong Student ID or Password. Please try again.");
}
}
}
?>
database
you button name is different from the one in php
//previous code button clicked for register
if (isset($_POST['reg_user'])) {}
instead of
//button clicked for register
if (isset($_POST['register'])) {}
and also your query
if your "id" an auto increment, leave it blank rather put 0, you can also do as follow
$query = "INSERT INTO users (name, surname, email, studentid, password,
course)VALUES('$name','$surname', '$email', '$studentid' '$password', '$course')";
UPDATED TO HELP ANYONE WITH SIMILAR ISSUE
For anyone that may have similar code challenge, please check if every semi column, comma and dot are where they should be.
You can debug also by echoing out the values to know where the problem is probably coming from.
Also read through the comments you might pick up what you need from there.
Hope this helped.
Problem is in your Query You take surname instead of username.
Change Query
From this
$query = "INSERT INTO users (name, surname, email, studentid, password, course)
VALUES(0,'$name','$surname', '$email', '$studentid' '$password', '$course')";
To this
$query = "INSERT INTO users (id, name, surname, email, studentid, password, course)
VALUES('$name','$username', '$email', '$studentid' '$password', '$course')";
And there are lots of spelling mistake in code. kindly fill relax and check all spelling.
I am not sure why I am getting the following errors for my code, I would be grateful if someone could explain it to me.
Managed to reduce all errors other than this one, I think the code is failing to check if the email is already registered but not sure why.
if (empty($_POST['email']))
{$errors[] = 'Please enter your email.';}
else
{$e = mysqli_real_escape_string($dbc,
trim($_POST['email']));}
if (empty($errors))
{
$q = "SELECT user_id FROM users WHERE email='$e'";
$r = mysqli_query ($dbc,$q);
if (mysqli_num_rows($r) != 0)
{$errors[] = 'Email address already registered.
Login';}
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result,
boolean given in C:\Abyss Web Server\htdocs\register1.php on line 59
<!DOCTYPE HTML>
<html lang="en">
<head><meta charset="UTF-8">
<title>Surf Shop Registration</title>
</head>
<body>
<?php
$page_title = 'Register';
include ('includes/header.html');
# conditional test to only execute contained statements if form has been submitted.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
# statements to be inserted here.
# open database connection and initialise array for error messages.
require ('../surfshop_db.php');
$errors = array();
# stores error msg if firstname field remains empty, or store value in a variable.
if (empty($_POST['first_name']))
{$errors[] = 'Please enter your first name.';}
else
{$fn = mysqli_real_escape_string($dbc,
trim($_POST['first_name']));}
# stores error msg if lastname field remains empty, or store value in a variable.
if (empty($_POST['last_name']))
{$errors[] = 'Please enter your last name.';}
else
{$ln = mysqli_real_escape_string($dbc,
trim($_POST['last_name']));}
# stores error msg if email field remains empty, or store value in a variable.
if (empty($_POST['email']))
{$errors[] = 'Please enter your email.';}
else
{$e = mysqli_real_escape_string($dbc,
trim($_POST['email']));}
# stores password as a variable if both password fields match, or store an error msg if not matching or first field is empty.
if (!empty($_POST['pass1']))
{
if ($_POST['pass1'] != $_POST['pass2'])
{$errors[] = 'Passwords do not match.';}
else
{$p = mysqli_real_escape_string($dbc,
trim($_POST['pass1']));}
}
else {$errors[] = 'Please enter your password.';}
# stores error msg if email already exists in database.
if (empty($errors))
{
$q = "SELECT user_id FROM users WHERE email='$e'";
$r = mysqli_query ($dbc,$q);
if (mysqli_num_rows($r) != 0)
{$errors[] = 'Email address already registered.
Login';}
}
# stores user data in database and displays a confirmation message when registration is successful, closes the database connection and includes a page footer as well as exit the script.
if (empty($errors))
{
$q = "INSERT INTO users
(first_name, last_name, email, password, reg_date)
VALUES ('$fn', '$ln', '$e', SHA1('$p'), NOW())";
$r = mysqli_query ($dbc,$q);
if ($r)
{
echo '<h1>Registered!</h1>
<p>You are now registered.</p>
<p>Login</p>';
}
mysqli_close($dbc);
include ('includes/footer.html');
exit();
}
# displays all stored error msg when registration fails and closes database connection.
else
{
echo '<h1>Error!</h1>
<p id="err_msg">The following error(s) occurred:<br>';
foreach ($errors as $msg)
{
echo " -$msg<br>";
}
echo 'Please try again.</p>';
mysqli_close($dbc);
}
}
?>
<!--Sticky HTML form-->
<h1>Register</h1>
<form action="register1.php" method="POST">
<p>
First Name: <input type="text" name="first_name"
value="<?php if (isset($_POST['first_name']))
echo $_POST['first_name'];?>">
Last Name: <input type="text" name="last_name"
value="<?php if (isset($_POST['last_name']))
echo $_POST['last_name'];?>">
</p><p>
Email Address: <input type="text" name="email"
value="<?php if (isset($_POST['email']))
echo $_POST['email'];?>">
</p><p>
Password: <input type="password" name="pass1"
value="<?php if (isset($_POST['pass1']))
echo $_POST['pass1'];?>">
Confirm Password: <input type="password" name="pass2"
value="<?php if (isset($_POST['pass2']))
echo $_POST['pass2'];?>">
</p><p>
<input type="submit" value="Register"> </p>
</form>
<?php include ('includes/footer.html');?>
</body>
</html>
I'm trying to insert data into the 'riders' table in the 'poo12104368' database using a form. Currently I am having problems with my 'if' statements because they are not working as they should be. For example, if a user was to only type in a last name and an email address, it would let them create an account. When the user does create an account by entering their correct details into the feilds it should take them to 'newaccount.php'. Can anybody help? Thanks
Code:
$firstnameErr = $lastnameErr = $suemailErr = "";
$firstname = $lastname = $suemail = "";
if(isset($_POST['submit2'])){
if(empty($_POST["firstname"])||(empty($_POST["lastname"]))||(empty($_POST["suemail"]))){
echo "Something is wrong";
if($_POST['firstname'] == null){
$firstnameErr = "First Name is required";
}else{
$firstname =($_POST["firstname"]);
}
if($_POST['lastname'] == null){
$lastnameErr = "Last Name is required";
}else{
$lastname = ($_POST["lastname"]);
}
if($_POST['suemail'] == null){
$suemailErr = "Email is required";
}else{
$suemail = ($_POST["suemail"]);
}
if($_POST['firstname'] == null){
echo "<b>Please enter a first name</b>";
}
else if($_POST['lastname'] == null){
echo "<b><p>Please enter a last name</p></b>";
}
else if($_POST['suemail'] == null){
echo "<b><p>Please enter an email</p></b>";
}
$dblink = mysql_connect("localhost", "root", "" )
or die (mysql_error());
mysql_select_db("poo12104368");
// Query the database to see if the email that the user has entered is already in use
$rs2 = mysql_query("SELECT * FROM riders WHERE Email = '".$_POST['suemail']."'");
if($row = mysql_fetch_assoc($rs2)){
$dbEmail = $row['Email'];
if($row['Email'] == $_POST['suemail']){
echo "<p><b>Email already used. Please use another</b></p>";
}
}
else{
// Insert query to insert the data into the riders table if their data meets the required inputs
$sql = "
INSERT INTO riders (FirstName, LastName, Email) VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['suemail']."')";
mysql_query($sql);
// The web page that the user will be taken to
header('Location:http://localhost/newaccount.php');
}
}
}
?>
<h2><p> Sign Up </p></h2>
<p><span class="error">* required field.</span></p>
<!-- Form that the users enters their data in -->
<form name = "suform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name:<input type="text" name="firstname" style="width:20%"/>
<span class="error">*<?php echo $firstnameErr;?></span></p></br>
<p>Last Name:<input type="text" name="lastname" style="width:20%"/>
<span class="error">*<?php echo $lastnameErr;?></span></p></br>
<p>Email Address:<input type="text" name="suemail" style="width:20%"/></p>
<span class="error">*<?php echo $suemailErr;?></span></br>
<p><br><input type="submit" name="submit2" value="Submit"/></br></p>
<h2>Our Links</h2>
<!-- Links to the various mediums for Bewdley Motorcycle Club -->
<p>YouTube:BewdleyMCCOffcial<p>
<p>Website:www.bewdleymotorcycleclub.co.uk</p>
Try this it will work :
Use flag to handle the validation errors in the form use this $error as a flag.
Code :
$firstnameErr = $lastnameErr = $suemailErr = "";
$firstname = $lastname = $suemail = "";
if(isset($_POST['submit2'])){
$error = 0;
if(empty($_POST["firstname"])||(empty($_POST["lastname"]))||(empty($_POST["suemail"]))){
$msg = "something going wrong";
$error = 1;
}
if($_POST['firstname'] == null){
$firstnameErr = "First Name is required";
$error = 1;
}else{
$firstname =($_POST["firstname"]);
}
if($_POST['lastname'] == null){
$lastnameErr = "Last Name is required";
$error = 1;
}else{
$lastname = ($_POST["lastname"]);
}
if($_POST['suemail'] == null){
$suemailErr = "Email is required";
$error = 1;
}else{
$suemail = ($_POST["suemail"]);
}
if($_POST['firstname'] == null){
$msg = "Please enter a first name";
$error = 1;
}
else if($_POST['lastname'] == null){
$msg = "Please enter a last name";
$error = 1;
}
else if($_POST['suemail'] == null){
$msg = "Please enter an email";
$error = 1;
}
if($error == '0')
{
$dblink = mysql_connect("localhost", "root" , "")
or die (mysql_error());
mysql_select_db("poo12104368");
// Query the database to see if the email that the user has entered is already in use
$rs2 = mysql_query("SELECT * FROM riders WHERE Email = '".$_POST['suemail']."'");
if($row = mysql_fetch_assoc($rs2)){
$dbEmail = $row['Email'];
if($row['Email'] == $_POST['suemail']){
echo "<p><b>Email already used. Please use another</b></p>";
}
}
else{
// Insert query to insert the data into the riders table if their data meets the required standards
$sql = "
INSERT INTO riders (FirstName, LastName, Email) VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['suemail']."')";
mysql_query($sql);
// The web page that the user will be taken to
header('Location:http://localhost/newaccount.php');
}
}
else
{
echo $msg;
}
?>
<h2><p> Sign Up </p></h2>
<p><span class="error">* required field.</span></p>
<!-- Form that the users enters their data in -->
<form name = "suform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name:<input type="text" name="firstname" style="width:20%"/>
<span class="error">*<?php echo $firstnameErr;?></span></p></br>
<p>Last Name:<input type="text" name="lastname" style="width:20%"/>
<span class="error">*<?php echo $lastnameErr;?></span></p></br>
<p>Email Address:<input type="text" name="suemail" style="width:20%"/></p>
<span class="error">*<?php echo $suemailErr;?></span></br>
<p><br><input type="submit" name="submit2" value="Submit"/></br></p>
<h2>Our Links</h2>
<!-- Links to the various mediums for Bewdley Motorcycle Club -->
<p>YouTube:BewdleyMCCOffcial<p>
<p>Website:www.bewdleymotorcycleclub.co.uk</p>
I hope it will work for you.
I have a registration form. In the database, the username and email are unique index. When the form submits and username or email are already present in the database, the values are not inserted. I want to notify the user that the values were not inserted. How can i do this?
HTML
<form action="register.php" method="post" id="reg" onsubmit='return validate();'>
Company Name:
<input type="text" class="inputs" name="name" id="name" /><br />
Email:
<input type="text" class="inputs" name="email" id="txtEmail" /><br />
User name:
<input type="text" class="inputs" name="uname" id="uname"/><br />
Password:
<input type="password" class="inputs" name="pass" id="pass1"/><br />
Conferm Password:
<input type="password" class="inputs" name="cpass" id="pass2"/><br /><br />
<input type="submit" value="Register" class="button" />
</form>
register.php:
include ("db.php");
if (isset($_POST['register'])) {
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
mysqli_query($con,"INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','')");
}
*Sweet And Short *
First check that username or email is exist or not using select query if resulting is 0 (it means not exists), Insert query will run ahead
<?php
if($_POST['register']){
$uname = $_POST['uname'];
$email = $_POST['email'];
$name= $_POST['name'];
$pass= $_POST['pass'];
$result = mysqli_query($con, 'SELECT * from TABLE_NAME where email_id = "'.$email.'" or username = "'.$uname.'" ');
if(mysqli_num_rows($result) > 0){
echo "Username or email already exists.";
}else{
$query = mysqli_query($con , 'INSERT INTO TABLE_NAME (`email_id`, `username`,`name`,`pass`) VALUES("'.$email.'", "'.$email.'", "'.$uname.'","'.$name.'", "'.$pass.'")');
if($query){
echo "data are inserted successfully.";
}else{
echo "failed to insert data.";
}
}
}
?>
The query method would return true or false, depending on if the row has been inserted or not.
Try the following Code
include ("db.php");
if (isset($_POST['register']))
{
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
$var = mysqli_query('SELECT * from company_profile where email_id = "'.$email.'" or username = "'.$uname.'" ');
$num = mysqli_num_rows($var);
if($num==0)
{
$result = INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','');
$res = mysqli_query($result);
if($res)
{
echo "Records Inserted Successfully!!";
}
else
{
echo "Records Inserted Failed!!";
}
}
else
{
echo "User with the Details Already exists!!"
}
}