MySQL and PHP help on how to make a registration form - php

Hi I am trying to make a registration form that sends input data to phpmyadmin's database I created. I think I mixed up MySQLI and MySQL any suggestions on how to fix would be great!! I just dont understand why my data is not being sent over to the database on phpmyadmin.
PHP:
// connect to database
$db = mysqli_connect("127.0.0.1", "root", "", "user logins");
if (isset($_POST['register_btn'])) {
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$emailAddress = mysql_real_escape_string($_POST['emailAddress']);
$password = mysql_real_escape_string($_POST['password']);
$password2 - mysql_real_escape_string($_POST['password2']);
}
if ($password == $password2) {
// create user
$password = md5($password); //hash password before storing for security
$sql = "INSERT INTO user logins(firstName, lastName, emailAddress, password) VALUES('$firstName', '$lastName' '$emailAddress', '$password')";
mysqli_query($db, $sql);
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header('location: homepage.html'); //redirect to homepage
} else {
$_SESSION['message'] = "The two passwords do not match";
}
?>
HTML:
<link rel="stylesheet" type="text/css" href="custom.css">
<body class="background">
<div>
<h1 class="header1">Sign in Below</h1>
</div>
<div>
<form action="connect.php" method="post">
<div>
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
</div>
<div>
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
</div>
<div>
<label for="emailAddress">Email Address:</label>
<input type="email" name="email" id="emailAddress">
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
</div>
<div>
<label for="password2">Repeat Password:</label>
<input type="password" name="password2" id="password2">
</div>
<input type="submit" name="register_btn" value="register">
</form>
</div>
</body>

Have you put in a password?
Is your database on your local machine?
Is your database table called user logins (with a space)
Is root your login?
Is your PHP file called connect.php?
Any error messages?
What happens when you click the form button
Sorry just a few things that crossed my mind that might help determine the problem.
You may just need to remove the following curly bracket
$password2 - mysql_real_escape_string($_POST['password2']);
}
and add it at the end of you file so it runs with your isset() function
$_SESSION['message'] = "The two passwords do not match";
}
}
?>

I don't think "user logins" is a valid table name. Change it to "user_logins", or at the very least, use the quote ` around the table name.
INSERT INTO `user logins`(
OR
INSERT INTO user_logins(
Second one you have to rename the table in phpmyadmin. As a general rule, you want to quote table names no matter what. Because sometimes your table name is a MySQL-reserved keyword. It's just good practice.
Also, the 4th parameter in mysqli_connect is database name. So is your database named "user logins"? Don't confuse table name with database name.

solved:(a small mistake)
this line is not a assignment :
$password2 - mysql_real_escape_string($_POST['password2']);
to
$password2 = mysql_real_escape_string($_POST['password2']);
( - ) must be converted to (=)

Related

Why doesn't my registration form insert the user data into the database?

I created a registration form using HTML, created a database called “web_app_dev" and linked the form to the database using PHP, however, when I test the form and click the Submit button nothing happens. It doesn't show me any errors and the information does not get posted into the database.
The table in the database is called "registration"
Below is the code for the "registerform.php"
<?php
session_start();
$FirstName = "";
$LastName = "";
$gender = "";
$email = "";
$password = "";
$errors = array();
// connect to database
$conn = mysqli_connect('localhost', 'root', '', 'web_app_dev');
// check if the registration button is clicked
if (isset($_POST['reg_btn'])) {
// Receive information from the form
$FirstName = mysqli_real_escape_string($conn, $_POST['FirstName']);
$LastName = mysqli_real_escape_string($conn, $_POST['LastName']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// make sure that the form is correctly filled
if (empty($FirstName)) {
array_push($errors, "First Name is required");
}
if (empty($LastName)) {
array_push($errors, "Last Name is required");
}
if (empty($gender)) {
array_push($errors, "Gender is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
//check if user already exists in the database
$user_check = "SELECT * FROM registration WHERE email='$email' LIMIT 1";
$result = mysqli_query($conn, $user_check);
$user = mysqli_fetch_assoc($result);
if ($user) {
if ($email['email'] == $email) {
array_push($errors, "A user with this email already exists");
}
}
//register the user if there are no errors
if (count($errors) == 0) {
$password = md5($password); //encrypt the password before saving it into the database
$query = "INSERT INTO registration (FirstName, LastName, gender, email, password)
VALUES('$FirstName', '$LastName', '$gender', '$email', '$password')";
mysqli_query($conn, $query);
$_SESSION['success'] = "Registration successful!";
}
}
?>
Below is the code from the html file that contains the html code for the form, the file's name is "regform.php"
<?php include('registerform.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" href="edits.css">
</head>
<body>
<style>
body {
background-image: url("img/bg2.jpg");
}
</style>
<div class="header">
<h2 style="margin-right: 60px;">Register</h2>
</div>
<form method="post" action="registerform.php">
<div class="input-group">
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName"
placeholder="Enter First Name..."/>
</div>
<div class="input-group">
<label for="LastName">Last Name</label>
<input type="text" name="LastName" id="LastName"
placeholder="Enter Last Name..."/>
</div>
<div class="radio-group">
<label for="m"><input type="radio" name="gender"
value="m">Male</label>
<label for="f"><input type="radio" name="gender"
value="f">Female</label>
</div>
<div class="input-group">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="Enter
Email...">
</div>
<div class="input-group">
<label for="password">Password</label>
<input type="text" name="password" id="password"
placeholder="Enter password...">
</div>
<div class="input-group">
<button type="submit" class="btn" id= "reg_btn"
name="reg_btn" value="reg_btn">Submit</button>
</div>
</form>
</body>
</html>
[Edit] Bellow is a screenshot of the error message that shows, after adding the error reporting code before the mysqli_connect() code.
Error message after filling in the form and clicking the register button
"Line 59" from the error message, is referring to the second last line from the registerform.php code. the code on that line is;
mysqli_query($conn, $query);
The data I put in the form is also shown bellow
Data inserted in the form
It's because you're inserting a hash of the password into the database, not the original password the user entered. md5 hashes usually come out at 32 characters (regardless of the length of the hashed data).
Note that - as you were warned above - md5 is obsolete now and insecure, it can be cracked easily. So should switch to using php's secure password_hash function. As per its documentation you need to allow at least 60 characters for storing a hash created by that function (but it advises 255 is better)

How to do the next step for login

I am learning MySQL and PHP and I trying to build a simple login webpage and connect with MySQL.
I have built the page with HTML and CSS, also I downloaded PHP and installed MySQL, I am getting confused about how to combine those things and when I input my password and username it will go to successful page.
I am not seeking an answer but need some suggestions for the next step.
PLEASE NOTE - the way my SQL queries are written here are open to SQL injection (see here to get the changes you would need to make)
So to start. You want to create a database table to store your users, a form to create users, and some code to query the data into the database.
i would start with a form like this:
<form method="post" class="mt-3">
<input type="hidden" name="do" value="create" />
<div class="form-group">
<label for="itemName">First Name</label>
<input type="text" class="form-control" name="firstName">
</div>
<div class="form-group">
<label for="serialNumber">Last Name</label>
<input type="text" class="form-control" name="lastName">
</div>
<div class="form-group">
<label for="serialNumber">Username</label>
<input type="text" class="form-control" name="userName">
</div>
<div class="form-group">
<label for="serialNumber">Password</label>
<input type="password" class="form-control" name="passWord">
</div>
<a id="create-member" class="btn btn-success text-white">Submit</a>
</form>
then you want some code that will take the values you have in that form and turn them into a query to add that info into your table.
if(isset($_POST['do'])) && $_POST['do'] == 'create'
{
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$username = $_POST['userName'];
$password = password_hash($_POST['passWord'], PASSWORD_BCRYPT);
$sql = "INSERT INTO members (first_name, last_name, username, password) VALUES ('".$firstName."', '".$lastName."', '".$username."', '".$password."')";
mysqli_query($conn, $sql); //$conn is set in my header file and included into every page.
}
That is pretty much the process for creating a user and adding it to your table, obviously you'll have to break it down and change values to what you have in your table etc.
Next it's the case of verifying a login.
first, a login form:
<form method="post">
<input type="hidden" name="do" value="login" />
<div class="form-group">
<label for="usename">Username</label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
and then an authentication query to follow, this will take the info in the login page, hash the password you entered and then compare it with the one in your database.
if (isset($_POST['do']) && $_POST['do'] == 'login')
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT id, first_name, last_name, password FROM members WHERE username= '$username'";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if($query->num_rows == 0)
{
echo "Username or password incorrect";
}else{
$data = mysqli_fetch_array($query);
if(!password_verify($password, $data['password']))
{
echo "Username or password incorrect";
}else{
session_regenerate_id();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['member_id'] = $data['id'];
$_SESSION['first_name'] = $data['first_name'];
$_SESSION['last_name'] = $data['last_name'];
}
}
}
}
?>
don't be scared about the $_SESSION variables at the bottom, i just set all user data as that so it's easier to access it on other pages, then i just follow with a header to my index.php page. In my header i also check to see that $_SESSION['loggedin'] is set to true and if not it redirects them to the login page (also be care to take into account the user might be on the login page, you dont want a redirect error)
This is my first detailed answer on this site so i hope it helps you :)

Why does my user registration form not work properly?

I am trying to create a user registration form using php and mysql. When I try to hit the submit button no new record is added to my database. The database is functional and has worked with other forms.
HTML/FORM
<?php
include 'header.php';
?>
<section>
<div class="form">
<form action="signup.php" method="post">
<h1> Sign Up!</h1>
<p>First name:
<input type="text" name="fName" maxlength="15" required pattern="^[a-zA-Z]{3,20}$" placeholder="Enter Name" />
</p>
<p>Last name:
<input type="text" name="lName" maxlength="15" pattern="^[a-zA-Z]{3,20}$" required placeholder="Enter Last Name" />
</p>
<p>Email:
<input type="email" name="email" maxlength="40" required placeholder="Enter Email" />
</p>
<p>Username:
<input type="text" name="username" maxlength="20" ^[A-Za-z0-9_]{1,15}$ required placeholder="Enter Username" />
</p>
<p>Password:
<input type="password" name="password" maxlength="20" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required placeholder="Enter Password" />
</p>
<p>Re-type Password:
<input type="password" name="password2" maxlength="20" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" required placeholder="Re-type Password" />
</p>
<p>
<button type="submit" name="signupbutton"> Sign up </button>
</p>
</form>
</div>
</section>
<div class="footerspecial">
<?php
include 'footer.php';
?>
</div>
PHP/SQL
<?php
//have they submitted at least once?
if(isset($POST['$password2'])){
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
//do the passwords NOT match?
if ($password !== $password2) {//do string comparison here
echo'<h2>Error: passwrods don\'t match!</h2>';
require ('registerform.php');
}
else {
//does the username already exist?
$sql = mysql_query("SELECT * FROM users WHERE username=='$username'");
if ($results=$con->query($sql)){
echo'<h2>Error: username is already taken</h2>';
require ('registerform.php');
}
else {
$sql = mysql_query("SELECT * FROM users WHERE email=='$email'");
if ($results=$con->query($sql)){
echo'<h2>Error: email already used</h2>';
require ('registerform.php');
}
else {
// If the values are posted, insert them into the database.
$sql= "INSERT INTO users (fName, lName, email, username, password, password2) VALUES ('$fName', '$lName', '$email', '$username', '$password', $password2)";
if (!$con->query($sql)){
echo 'Error: coulndt do suff';
}
else {
echo 'Account made';
}//ENDS SUCCESSFUL INSURT
}//ENDS EMAIL VALIDATION
}//ENDS THE USERNAME VALIDATION
}//END PASSWORD VALIDATION
}
?>
Picture of the form don't really know if its helpful but ya'know
https://gyazo.com/418b86ecb5090604a1f229e1e94fe3bf
I'm guessing here that your database doesn't have a password2 column (seems kind of pointless to have) so trying to insert into it will give an error.
You should read about MySQLi error reporting
Also add error_reporting(-1); at the start of your PHP file to show PHP errors.
P.S. your code is vulnerable to SQL injection, you should use prepared statements to be safe from this.
Could have multiple problems first you do not have the single quotes around $password2. This could be leading to a failed insert.
VALUES ('$fName', '$lName', '$email', '$username', '$password', $password2)";
Also I would echo the sql errors out as you are not doing. you can do this easily. Test the if statement for a true not a false
if ($con->query($sql)){
//if true then runs your code;
}
else {
echo "Error: " . $sql . "<br>" . $con->error; // This will echo out any sql errors you may have
}

Cannot insert data into database (php/mysqli) (Phpstorm 9/Wamp) [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I have an issue with inserting the data that I gather from one of my forms into my database.
Each form adds data to a different table in the database(one into users and one into tasks).
I use one form for registration and I'll paste the important parts of the code below(this one is working).
This is the form part of the Register.php file
<form method="post" action="register_code.php">
<div class="FormElement">
<input name="user_name" type="text" class="Tfield" id="user_name" required placeholder="User Name">
</div>
<div class="FormElement">
<input name="password" type="password" class="Tfield" id="password" required placeholder="Password">
</div>
<div class="FormElement">
<input name="email" type="email" class="Tfield" id="email" required placeholder="E-mail">
</div>
<div class="FormElement">
<input name="first_name" type="text" class="Tfield" id="first_name" required placeholder="First Name">
</div>
<div class="FormElement">
<input name="last_name" type="text" class="Tfield" id="last_name" required placeholder="Last Name">
</div>
<div class="FormElement">
<input type="submit" id="Register" name="Register" value="Register" class="button">
</div>
This is the register_code.php file
<?php
require "DBconnect.php";
$post = $_POST;
if(isset($post)) {
session_start();
$UName = $post['user_name'];
$PW = md5($post['password']);
$FName = $post['first_name'];
$LName = $post['last_name'];
$Email = $post['email'];
$sql = $con->query("INSERT INTO users (user_name, password, email, first_name, last_name) VALUES ('$UName','$PW','$Email', '$FName', '$LName')");
if($sql)
header("Location: Registration_successful.php");
else
echo "Please try again to register";
}
include 'Register.php';
And another form I use to add data into another table(named tasks). The data I gather from this file will not insert into my database for some reason.
This is the form part of the Add_Task.php file:
<form method="post" action="Add_Task_code.php">
<div class="FormElement">
<input name="TName" type="text" class="Tfield" id="TName" required placeholder="Task name">
</div>
<div class="FormElement">
<input name="TDesc" type="text" class="TextField" id="TDesc" required placeholder="Task summary">
</div>
<div class="FormElement">
<input type="submit" id="Submit" name="Submit" value="Submit" class="button">
</div>
</form>
And this is the code from the Add_Task_code.php file
<?php
require 'DBconnect.php';
$post=$_POST;
if(isset($post))
{
$TaskName = $post['TName'];
$TaskDesc = $post['TDesc'];
$sqltask="INSERT INTO tasks ('TName','TDesc') VALUES ('$TaskName','$TaskDesc')";
if ($con->query($sqltask))
header("Location: Tasks.php");
else
header("Location: Add_Task.php");
}
?>
The file DBconnect.php only contains this:
<?php
$con= mysqli_connect("localhost", "root","","first_app")
?>
The problem is that even though the code is similar in both forms only one of them is working. Every time I run the Add_Task.php file it redirects me to the same page (as I instructed it) since it does not add anything to the database.
I also checked the tables just in case it adds something but it does not.
please set your primary_key(id) as auto increment in table tasks. if you not set it might be possible.
and change this line
$sqltask="INSERT INTO tasks ('TName','TDesc') VALUES ('$TaskName','$TaskDesc')";
like this :
$sqltask="INSERT INTO tasks (TName,TDesc) VALUES ($TaskName,$TaskDesc)";
You are mixing OOP style and Procedural Style in your code
You are used Procedural Style in your DBconnect.php file. And You are missing ; in your connection file.
DBconnect.php file should be:
<?php
$con= mysqli_connect("localhost", "root","","first_app");
?>
register_code.php code should be:
<?php
require "DBconnect.php";
$post = $_POST;
if(isset($post)) {
session_start();
$UName = $post['user_name'];
$PW = md5($post['password']);
$FName = $post['first_name'];
$LName = $post['last_name'];
$Email = $post['email'];
$sql = mysqli_query($con,"INSERT INTO users (user_name, password, email, first_name, last_name) VALUES ('$UName','$PW','$Email', '$FName', '$LName')");
if($sql)
header("Location: Registration_successful.php");
else
echo "Please try again to register";
}
include 'Register.php';
Add_Task_code.php file code should be:
<?php
require 'DBconnect.php';
$post=$_POST;
if(isset($post))
{
$TaskName = $post['TName'];
$TaskDesc = $post['TDesc'];
$sqltask="INSERT INTO tasks ('TName','TDesc') VALUES ('$TaskName','$TaskDesc')";
if (mysqli_query($con,$sqltask))
header("Location: Tasks.php");
else
header("Location: Add_Task.php");
}
?>
Try to make the below changes and see what the actual error is.then debug your code.
if($_SERVER['REQUEST_METHOD']=='POST')
{
$TaskName = $post['TName'];
$TaskDesc = $post['TDesc'];
$sqltask="INSERT INTO tasks ('TName','TDesc') VALUES ('$TaskName','$TaskDesc')";
if ($con->query($sqltask))
echo "Successfully Inserted";
else
echo "Error: " . $sqltask. "<br>" . mysqli_error($conn);
}
?>

If(..){include}, includes anyways

I am trying to make a simple Login system for admins. Nothing too special, since it's my first one. I am trying to verify if the username and password inputted are the same as the one in the database, and then include the rest of the page. No errors, everything works as it should, the database access is good, but it's like the if statement isn't there. It just includes the rest of the page on load.
<form action="admin.php" method="POST" class="login">
<input type="text" placeholder="Password" name="username" required>
<input type="password" placeholder="Password" name="password" required>
<input type="submit" value="Log In">
</form>
<?php
require('connect.php');
$admin = <<<SQL
SELECT *
FROM admins
SQL;
$username = $_POST['username'];
$pw = $_POST['password'];
$result = $db->query($admin);
while($row = $result->fetch_assoc()){
if($username == $row['username'] && $pw == $row['password']){
include('admininclude.php');
} else {
echo 'You are not cool enought to enter. (Username or Password wrong.)';
}
}
$db->close();
?>
Thanks in advance!

Categories