hi guys please l need some help. lm setting up a user registration sign up form. but l was NOT ABLE TO INSERT THE USER INFO IN TO THE DATABASE. And the code did not display any error message, meaning that everything is fine.
But when l tried to sign up it gives the form's error message "Failed to Register User".
this is the code: (and check at the bottom the connect.php code)
<?php
require_once('connect.php');
//print_r($_POST);
if(isset($_POST) & !empty($_POST)) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// storing the sign up info in to the database
$sql = "INSERT INTO usermanagement (username, email, password) VALUES ('$username', '$email', '$password')";
//executing the query
$result = mysqli_query($connection, $sql);
if($result){
echo "User Registered Successfully";
}
else{
echo "Failed to Register User";
}
}
?>
<div id="form-signup">
<form id="signup-form" name="sign-up" action="sign.php" method="POST">
<h1>Create your profile</h1>
<p>
<input type="text" name="username" id="username" class="signup-input" required="required" placeholder="Full name*" >
</p>
<p>
<input type="email" name="email" class="signup-input" required="required" placeholder="Email*" >
</p>
<p>
<input type="password" name="password" class="signup-input" required="required" placeholder="Mot de passe*">
</p>
<!-- <p>
<input type="password" name="confirmpassword" class="signup-input" required="required" placeholder="Confirmez mot de passe*">
</p> -->
<p class="agree"> By signing up, you agree to Tout-Passe's <br> Terms of use<br> and Privacy Policy.
</p>
<p>
<input type="submit" class="signup-btn" name="btn-signup" value="Create Account">
</p>
<p class="already">Already on Tout-Passe? Log in</p>
</div><!--END OF PHASE-1-->
</form> <!--END OF SIGN-UP-->
</div><!--END FO ALLFORM-->
CONNECT CODE
<?php
$connection = mysqli_connect('localhost', 'root', '');
if(!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'listing');//listing = database
if(!$select_db){
die("Failed to select database" . mysqli_error($connection));
}
?>
You did a mistake line 4, if(isset($_POST) & !empty($_POST)) { you have only one & you should have two like this: if(isset($_POST) && !empty($_POST)) {
Beside this, when your message tell you that it failed to register the user, it does not explain why, to solve this you have to add a mysqli_error() like this:
require_once('connect.php');
//print_r($_POST);
if(isset($_POST) && !empty($_POST)) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// storing the sign up info in to the database
$sql = "INSERT INTO usermanagement (username, email, password) VALUES ('$username', '$email', '$password')";
//executing the query
$result = mysqli_query($connection, $sql);
if($result){
echo "User Registered Successfully";
}
else{
echo "Failed to Register User, reason: " . mysqli_error($connection);
}
}
Also there is two problems with your code:
It is faillibe to SQL injection. What is SQL injection?
You should test each of your global variables are set individually like this: if(isset($_POST['username']) && !empty($_POST['username'])) and not like this: if(isset($_POST) && !empty($_POST))
Related
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.
I have 2 problems.
Basic story: I have created a SIMPLE registration and login system.
Problem1: If I try to register a new account then it says "user registration failed". At the moment it should say that because mysql can't get right information from forms. But problem is that I don't know why. Everything seems correct...
Problem2: If I try to login with existent account then it seems that browser is only refreshing the page and nothing else...
Registration with php code:
<?php
require ('insert.php');
// If values posted, insert into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$name = $_POST['name'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
// nimi refers to name, it's correct
$query = "INSERT INTO `user` (nimi, email, username, password)
VALUES('$name', '$email', '$username', '$password')";
//POST retrieves the data.
$result = mysqli_query($connection, $query);
if($result){
$smsg = "User Created Successfully.";
} else {
$fmsg = "User Registration Failed";
}
}
mysqli_close($connection);
?>
<html>
...
<body>
...
<div>
<form method="POST" class="form-horizontal" role="form">
<!-- Status, how registering went -->
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<!-- Registration form starts -->
<h2>Form</h2><br>
<label for="Name"></label>
<input name="name" type="text" id="name" maxlength="40" placeholder="Ees- ja perenimi" class="form-control" autofocus> <!-- lopp -->
<label for="email"></label>
<input name="email" type="email" id="email" maxlength="65" placeholder="Email" class="form-control"> <!-- lopp -->
<label for="Username"></label>
<input name="username" type="text" id="userName" maxlength="12" placeholder="Kasutajatunnus/kasutajanimi" class="form-control" required> <!-- lopp -->
<label for="Password"></label>
<input name="password" type="password" id="password" maxlength="12" placeholder="Parool" class="form-control" required>
<button type="submit" class="btn btn-primary btn-block">Join</button>
</form> <!-- /form -->
</div> <!-- ./container -->
...
</body>
</html>
Login:
<?php
session_start();
require ('insert.php');
//Is username and password typed?
if (isset($_POST['username']) and isset($_POST['password'])){
//Making vars from inputs
$username = $_POST['username'];
$password = $_POST['password'];
//Checking existent of values.
$query = "SELECT * FROM `liikmed`
WHERE username='$username'
and password='$password'";
$result = mysqli_query($connection, $query)
or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
//3.1.2 If values equal, create session.
if ($count == 1){
$_SESSION['username'] = $username;
} else {
//If credentials doesn't match.
$fmsg = "Invalid Login Credentials.";
}
}
//if user logged in, welcome with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hai " . $username . "";
echo "This is the Members Area";
echo "<a href='logout.php'>Logout</a>";
}else{}
?>
<html>
...
<body>
...
<div id="bg"></div>
<form method="POST" class="form-horizontal">
<h2>Login</h2><br>
<label for="User"></label>
<input name="username" type="text" maxlength="15" placeholder="Username" class="form-control" required autofocus>
<label for="Password"></label>
<input name="password" type="password" maxlength="50" placeholder="Password" class="form-control" required autofocus>
<button type="submit" class="btn btn-primary btn-block">Enter</button>
</form>
</div>
...
</body>
</html>
And finally php database connection file (called insert.php):
<?php
$connection=mysqli_connect("localhost","root","pw");
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'my_database');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
First of all in your login PHP code, you only started a session but you didn't tell the from where to direct to if login is successful. Add a header to the code. That is;
if ($count == 1){
$_SESSION['username'] = $username;
header("Location: page.php"); //the page you want it to go to
}
And your registration PHP code looks ok. Check your database table if you've misspelt anything there.
Your logic to set the $_SESSION['username'] requires that the username and password combination exists once in your database.
This might sound silly but can you confirm that this is the case (i.e. confirm that you have not created the same username and password combination).
Altering the logic to be > 1 would also get around this temporarily. So your code
if ($count == 1){
$_SESSION['username'] = $username;
}
should become
if ($count > 1){
$_SESSION['username'] = $username;
}
I have a registration form and I want it to connect to my database. I used phpmyadmin as my database. The code that I used to connect the two is below:
db.php
<?php
$hostname = "127.0.0.1";
$user = 'root';
$password = '';
$db = 'dbTest';
//connection to db
$conn = mysqli_connect("$hostname", "$user", "$password", "$db")or die(mysqli_error());
mysqli_select_db($conn, "peanat")or die(mysqli_error());
$username = $_POST['username'];
$password = $_POST['password'];
$username = strtolower(trim($_POST["username"]));
$username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
$checkUsername = mysqli_query($conn, "Select username * FROM users WHERE Username='$username'");
$numrows = mysqli_num_rows($checkUsername);
if($numrows!==1) {
echo "Username not available";
}else{
$sql = "INSERT INTO `users` (`Username`, `Password`) VALUES ('$username', '$password')";
if(!mysqli_query($conn, $sql)) {
die(mysqli_error());
} else {
echo "1 record added";
}
}
?>
this is my reg form
<form id="register" action="db.php" method="post" >
<div class="col-4">
<label>
Username
<input placeholder="" id="username" name="username">
</label>
</div>
<div class="col-4">
<label>Password
<input type="password" placeholder="" id="password" name="password">
</label>
</div>
<div class="col-4">
<label>Confirm Password
<input type="password" placeholder="" id="password2" name="password2">
</label>
</div>
<div class="col-submit">
<input type="submit" class="submitbtn" name="register" value="Register">
</div>
</form>
now the problem I'm encountering is, every time I click the register button, it just goes to the designated page and it shows the code of that page. where do you think is my error...
Place the two files (db.php & reg.HTML) into your local web server folder. (eg. C:/xampp/htdocs/form/
Open any internet browser and type in the path to your HTML file. Eg. Local host/form/reg.html and hit enter.
You should get HTML form displayed on the browser and you're done.
I think I am successfully connecting to my database by:
<?php
$user = 'root';
$pass = '9KSroMDjEqNmEYY4';
$db = 'chatservice';
$host = '127.0.0.1';
$conn = new mysqli($host, $user, $pass, $db, 3306) or die("Unable to connect");
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
?>
My question is how I would use the registration code to successfully add a user to the database. When entering the form I press register I do not get any error messages stating that the registration didn't succeed. It seems that the php code is not being reached after the initial connection. I am new to php and mySQL so any tips on formatting would be nice too!
<?php
require('connect.php');
if(isset($_POST['user']) && isset($_POST['password'])){
$user = $_POST['user'];
$id = $_POST['IDNUM'];
$password = $_POST['password'];
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', '$id', '$password')";
$result = mysqli_query($query);
if($result){
$msg = "Registered Sussecfully";
echo $msg;
}
else
$msg = "Error Registering";
echo $msg;
}
?>
<div class="register-form">
<title>Chat Page Start</title>
<form action="" methods="POST">
<p>
<label>Username: </label>
<input id="user" type="text" name="user" placeholder="user" />
</p>
<p>
<label>ID: </label>
<input id="IDNUM" type="text" name="IDNUM" placeholder="ID number" />
</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" value="Register" />
</form>
</div>
Another thing is how would I check the status of my database connection and where I should be checking this status?
your database connection is mysqli_connect and you execute the query in mysql_query is not proper.
<?php
require('connect.php');
if(isset($_POST['user']) && isset($_POST['password'])){
$user = $_POST['user'];
$id = $_POST['IDNUM'];
$password = $_POST['password'];
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', ' $id ', '$password')";
$result = mysqli_query($query,$conn);
if($result){
$msg = "Registered Sussecfully";
}
else
$msg = "Error Registering";
}
?>
You are connecting database using mysqli:
$conn = new mysqli('localhost', $user, $pass, $db, 3306) or die("Unable to connect");
And executing query using mysql:
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', '$IDNUM', '$password')";
$result = mysql_query($query);
I have thoroughly researched my topic before coming here and can't seem to figure out my problem.
I have an HTML page:
<form role="form" action="register.php" method="POST">
<div class="form-group">
<label>First Name:</label>
<input type="text" name="first_name">
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" name="last_name">
</div>
<div class="form-group">
<label>Student ID:</label>
<input type="number" name="student_id">
</div>
<div class="form-group">
<label>Email address:</label>
<input type="email" name="email">
</div>
<button type="submit" name="register" value="register">Register</button>
</form>
<form role="form" action="login.php" method="POST">
<div class="form-group">
<label>Email address:</label>
<input type="email" name="email">
</div>
<button type="submit" name="login" value="login">Login</button>
</form>
This functions and communicates perfectly well with my login page written in php, it checks if the submitted email address already exists in a MySQL database. It will then point the user to a profile page and the code exits itself.
My issue is with my register page, I use the same MySQL SELECT functions that I do on my login page, to check and see if the submitted student ID or email already exists in the database and if so, will return back to the form for the user to try again:
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$student_id = $_POST['student_id'];
$email = $_POST['email'];
if (isset($_POST['register'])) {
register($conn, $first_name, $last_name, $student_id, $email);
}
function register($conn, $first_name, $last_name, $student_id, $email) {
$Ssql = "SELECT student_id FROM AidenLocke where student_id = '$student_id'";
$Sresult = mysqli_query($conn, $sql);
if (mysqli_num_rows($Sresult) > 0) {
header('Location: form.html');
} else {
$sql = "INSERT INTO AidenLocke (first_name, last_name, email, student_id)
VALUES ('$first_name', '$last_name', '$email', '$student_id')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br />" . $conn->error;
}
header('Location: profile.php');
}
}
(I have removed my database information for security reasons but there is no connection problem)
My main issue is with the else section of the second if statement, my code does not check if the student id already exists, and regardless of what information I enter into the form, makes a new entry in to the database.
I am quite confused and hoping someone can give me a valid answer, thanks!
You seem to have a typo in your variable when you query the database:
$Ssql = "SELECT student_id FROM AidenLocke where student_id = '$student_id'";
^^^^
$Sresult = mysqli_query($conn, $sql);
^^^
That is, you're using $sql instead of $Ssql