Simple Registration Form in PHP with Validation | Tutsmake.com

Содержание
  1. Login and Registration Form in PHP + MySQL using XAMPP
  2. Login and Registration Form in PHP and MySQL using XAMPP
  3. Step 1 – Open the XAMPP Control Panel & Create PHP Project
  4. Step 2 – Create Database and Table
  5. Step 3 – Create a Database Connection File
  6. Step 4 – Create registration form and Insert data into MySQL database
  7. Step 5 – Create Login Form In PHP with MySQL
  8. Step 6 – Create User Profile and Fetch data From Database
  9. Step 7 – Create Logout.php file
  10. Conclusion
  11. Форма регистрации на PHP с использованием базы данных MySQL
  12. Подключаемся к БД
  13. Создаем форму регистрации
  14. Смотрим результат
  15. Create Registration form with MySQL and PHP
  16. Contents
  17. 1. Table structure
  18. 2. Configuration
  19. 4. Form Submit
  20. 5. Demo
  21. 6. Conclusion
  22. PHP: Форма входа и регистрации в PHP + MySQL
  23. Шаг 1 — Откройте панель управления сервера и создайте проект PHP
  24. Шаг 2 — Создайте базу данных и таблицу
  25. Шаг 3 — Создайте файл подключения к базе данных
  26. Шаг 4 — Создайте регистрационную форму и вставьте данные в базу данных MySQL
  27. Шаг 5 — Создайте форму входа в PHP с MySQL
  28. Шаг 6 — Создайте профиль пользователя и получите данные из базы данных
  29. Шаг 7 — Создайте файл Logout.php

Login and Registration Form in PHP + MySQL using XAMPP

Simple login and registration form in PHP + MySQL + Boostrap using xampp. In this tutorial; you will learn how to create a simple login and registration form in PHP and MySQL using xampp with source code.

You can also download the complete source code of simple login and registration form in PHP + MYsql + Bootstrap using xampp from github.

Читайте также:  Установка python precompile standard library

Login and Registration Form in PHP and MySQL using XAMPP

  • Step 1 – Open the XAMPP Control Panel & Create PHP Project
  • Step 2 – Create Database and Table
  • Step 3 – Create a Database Connection File
  • Step 4 – Create a registration form and Insert data into MySQL database
  • Step 5 – Create Login Form in PHP with MySQL
  • Step 6 – Create User Profile and Fetch Data From MySQL Database
  • Step 7 – Create Logout.php file

Step 1 – Open the XAMPP Control Panel & Create PHP Project

Visit your xampp installed directory. Then open xampp control panel and start it; then visit xampp/htdocs directory. And inside this directory create php project directory.

Step 2 – Create Database and Table

Create a database name my_db and execute the below-given query in your database. The below query will create a table named users in your database with the following fields like uid, name, email, mobile:

CREATE DATABASE my_db; CREATE TABLE `users` ( `uid` bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `mobile` varchar(255) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Step 3 – Create a Database Connection File

Create a file name db.php and update the below code into your file.

The below code is used to create a MySQL database connection in PHP. When you insert form data into MySQL database, there you will include this file:

Step 4 – Create registration form and Insert data into MySQL database

Create registration form file; which name registration.php. And add the following code into it:

 if (isset($_POST['signup'])) < $name = mysqli_real_escape_string($conn, $_POST['name']); $email = mysqli_real_escape_string($conn, $_POST['email']); $mobile = mysqli_real_escape_string($conn, $_POST['mobile']); $password = mysqli_real_escape_string($conn, $_POST['password']); $cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']); if (!preg_match("/^[a-zA-Z ]+$/",$name)) < $name_error = "Name must contain only alphabets and space"; >if(!filter_var($email,FILTER_VALIDATE_EMAIL)) < $email_error = "Please Enter Valid Email ID"; >if(strlen($password) < 6) < $password_error = "Password must be minimum of 6 characters"; >if(strlen($mobile) < 10) < $mobile_error = "Mobile number must be minimum of 10 characters"; >if($password != $cpassword) < $cpassword_error = "Password and Confirm Password doesn't match"; >if(mysqli_query($conn, "INSERT INTO users(name, email, mobile_number ,password) VALUES('" . $name . "', '" . $email . "', '" . $mobile . "', '" . md5($password) . "')")) < header("location: login.php"); exit(); >else < echo "Error: " : "" . mysqli_error($conn); >mysqli_close($conn); > ?>       

Please fill all fields in the form

Already have a account?Login

Step 5 – Create Login Form In PHP with MySQL

Create login form, where you accept user email id and password and authenticate users from database. So you can create a login.php file and add the below code into your file:

 if (isset($_POST['login'])) < $email = mysqli_real_escape_string($conn, $_POST['email']); $password = mysqli_real_escape_string($conn, $_POST['password']); if(!filter_var($email,FILTER_VALIDATE_EMAIL)) < $email_error = "Please Enter Valid Email ID"; >if(strlen($password) < 6) < $password_error = "Password must be minimum of 6 characters"; >$result = mysqli_query($conn, "SELECT * FROM users WHERE email = '" . $email. "' and pass = '" . md5($password). "'"); if(!empty($result)) < if ($row = mysqli_fetch_array($result)) < $_SESSION['user_id'] = $row['uid']; $_SESSION['user_name'] = $row['name']; $_SESSION['user_email'] = $row['email']; $_SESSION['user_mobile'] = $row['mobile']; header("Location: dashboard.php"); >>else < $error_message = "Incorrect Email or Password. "; >> ?>       

Please fill all fields in the form


You don't have account?

Step 6 – Create User Profile and Fetch data From Database

Create a new file name dashboard.php and add the below code into your file.

The below code used to show logged in user data.

 ?>      Logout 

Step 7 – Create Logout.php file

Create logout.php file and update the below code into your file.

The below code is used to destroy login your data and logout.

Conclusion

Simple login and registration form in php with mysql database using xampp; In this tutorial, you have learned how to create a simple login, registration and logout system in PHP MySQL with validation. Also, you have learned how to authenticate and logout logged in users in PHP.

Источник

Форма регистрации на PHP с использованием базы данных MySQL

Наша задача состоит в том, чтобы создать форму регистрации и обработчик на языке PHP, в которой, если пользователь вводит данные, То данные HTML-формы сохраняются в нашу базу данных MySQL.

Подключаемся к БД

Примечание: здесь не используется код CSS, поскольку мы используем Bootstrap в коде PHP ниже. Вы можете применить CSS стили в своих приложениях, если захотите.

Для соединения с БД создадим PHP файл «dbconnect.php», а имя для нашей базы базы данных выберем — «testdatabase».

Таблица «users » создается с помощью инструмента MySQL phpMyAdmin, как показано ниже.

Создаем форму регистрации

теперь, когда мы успешно подключились к нашей базе данных, пора создать форму регистрации для пользователей. Следующий код описывает нашу форму регистрации. Используемое имя таблицы базы данных MySql — «users».

 > else < $showError = "Passwords do not match"; >> if($num>0) < $exists="Username not available"; >>//end if ?>          Success! Your account is now created and you can login.   '; > if($showError) < echo ' 
Error! '. $showError.'
'; > if($exists) < echo '
Error! '. $exists.'
'; > ?>

Username
Password
Confirm Password Make sure to type the same password

Смотрим результат

Источник

Create Registration form with MySQL and PHP

In membership-based website registration and login page is common.

User needs to create a new account and login to the website to access services and manage its account.

In this tutorial, I show how you can create a signup page with MySQL and PHP.

Create registration form with MySQL and PHP

Contents

1. Table structure

I am using users table in the example.

CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `fname` varchar(80) NOT NULL, `lname` varchar(80) NOT NULL, `email` varchar(80) NOT NULL, `password` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a new config.php file for database configuration.

Completed Code

Success! ?>
First Name:
Last Name:
Email address:
Password:
Confirm Password:

4. Form Submit

Add the following code in section.

On submit assign $_POST values in variables.

  1. First, check if all values are entered or not. If not entered then assign false to $isValid and «Please fill all fields.» to $error_message .
  2. Check if entered password and confirm password are equal or not. If not equal then assign false to $isValid and «Confirm password not matching.» to $error_message .
  3. Check if $email variable value has a valid email or not. If not valid then assign false to $isValid and «Invalid Email-ID.» to $error_message .
  4. Check if email-id already exists in users table or not. If available then assign false to $isValid and «Email-ID is already existed.» to $error_message .

If $isValid has true value then insert a new record in the users table and assign «Account created successfully.» to $success_message .

Completed Code

 // Check if confirm password matching or not if($isValid && ($password != $confirmpassword) ) < $isValid = false; $error_message = "Confirm password not matching"; >// Check if Email-ID is valid or not if ($isValid && !filter_var($email, FILTER_VALIDATE_EMAIL)) < $isValid = false; $error_message = "Invalid Email-ID."; >if($isValid)< // Check if Email-ID already exists $stmt = $con->prepare("SELECT * FROM users WHERE email = ?"); $stmt->bind_param("s", $email); $stmt->execute(); $result = $stmt->get_result(); $stmt->close(); if($result->num_rows > 0) < $isValid = false; $error_message = "Email-ID is already existed."; >> // Insert records if($isValid)< $insertSQL = "INSERT INTO users(fname,lname,email,password ) values(. )"; $stmt = $con->prepare($insertSQL); $stmt->bind_param("ssss",$fname,$lname,$email,$password); $stmt->execute(); $stmt->close(); $success_message = "Account created successfully."; > > ?>

5. Demo

6. Conclusion

In this tutorial, I only cover the registration system and if you want to know how to create a login page then you can view the following tutorial.

If you found this tutorial helpful then don’t forget to share.

Источник

PHP: Форма входа и регистрации в PHP + MySQL

Простая форма входа и регистрации в PHP + MySQL + Boostrap. В этом руководстве вы узнаете, как создать простую форму входа и регистрации в PHP + MySQL. Мы будем использовать локальный сервер OpenServer

Шаг 1 — Откройте панель управления сервера и создайте проект PHP

Посетите каталог OpenServer/domains. И внутри этого каталога создайте каталог проекта php (назовите его например: auth.loc). Затем перезагрузите сервер, для того, чтобы в списке «Мои проекты» у вас появился ваш только что созданный проект.

Шаг 2 — Создайте базу данных и таблицу

Перейдите в панель управления сервером во вкладку «Дополнительно -> PhpMyAdmin«. Авторизуйтесь в ней и создайте базу данных с именем my_db и выполните приведенный ниже запрос в своей базе данных. Приведенный ниже запрос создаст таблицу с именем users в вашей базе данных со следующими полями, такими как uid, name, email, mobile:

CREATE DATABASE my_db; CREATE TABLE `users` ( `uid` bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `mobile` varchar(255) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Шаг 3 — Создайте файл подключения к базе данных

Создайте файл с именем db.php и обновите приведенный ниже код в своем файле.

Приведенный ниже код используется для создания подключения к базе данных MySQL в PHP. Когда вы вставляете данные формы в базу данных MySQL, вы подключаете туда этот файл:

Шаг 4 — Создайте регистрационную форму и вставьте данные в базу данных MySQL

Создать файл регистрационной формы с именем registration.php и добавьте в него следующий код:

 if (isset($_POST['signup'])) < $name = mysqli_real_escape_string($conn, $_POST['name']); $email = mysqli_real_escape_string($conn, $_POST['email']); $mobile = mysqli_real_escape_string($conn, $_POST['mobile']); $password = mysqli_real_escape_string($conn, $_POST['password']); $cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']); if (!preg_match("/^[a-zA-Z ]+$/", $name)) < $name_error = "Name must contain only alphabets and space"; >if (!filter_var($email, FILTER_VALIDATE_EMAIL)) < $email_error = "Please Enter Valid Email ID"; >if (strlen($password) < 6) < $password_error = "Password must be minimum of 6 characters"; >if (strlen($mobile) < 10) < $mobile_error = "Mobile number must be minimum of 10 characters"; >if ($password != $cpassword) < $cpassword_error = "Password and Confirm Password doesn't match"; >if (mysqli_query($conn, "INSERT INTO users(name, email, mobile_number ,password) VALUES('" . $name . "', '" . $email . "', '" . $mobile . "', '" . md5($password) . "')")) < header("location: login.php"); exit(); >else < echo "Error: " . mysqli_error($conn); >mysqli_close($conn); > ?>       

Registration Form in PHP with Validation

Please fill all fields in the form

Already have a account?Login

Шаг 5 — Создайте форму входа в PHP с MySQL

Создайте форму входа в систему, в которой вы принимаете идентификатор электронной почты и пароль пользователя и аутентифицируете пользователей из базы данных. Таким образом, вы можете создать файл login.php и добавить в свой файл приведенный ниже код:

 if (isset($_POST['login'])) < $email = mysqli_real_escape_string($conn, $_POST['email']); $password = mysqli_real_escape_string($conn, $_POST['password']); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) < $email_error = "Please Enter Valid Email ID"; >if (strlen($password) < 6) < $password_error = "Password must be minimum of 6 characters"; >$result = mysqli_query($conn, "SELECT * FROM users WHERE email = '" . $email . "' and pass = '" . md5($password) . "'"); if (!empty($result)) < if ($row = mysqli_fetch_array($result)) < $_SESSION['user_id'] = $row['uid']; $_SESSION['user_name'] = $row['name']; $_SESSION['user_email'] = $row['email']; $_SESSION['user_mobile'] = $row['mobile']; header("Location: dashboard.php"); >> else < $error_message = "Incorrect Email or Password. "; >> ?>       

Login Form in PHP with Validation

Please fill all fields in the form


You don't have account?Click Here

Шаг 6 — Создайте профиль пользователя и получите данные из базы данных

Создайте новый файл с именем dashboard.php и добавьте в него приведенный ниже код.

Приведенный ниже код используется для отображения данных пользователя, вошедшего в систему.

 ?>       
Name :- Email :- Mobile :- Logout

Шаг 7 — Создайте файл Logout.php

Создайте файл logout.php и обновите приведенный ниже код в свой файл.

Приведенный ниже код используется для уничтожения входа в систему и выхода из системы.

Простая форма входа и регистрации на php с базой данных mysql с использованием OpenServer; В этом руководстве вы узнали, как создать простую систему входа, регистрации и выхода из системы в PHP MySQL с проверкой. Кроме того, вы узнали, как аутентифицировать и выходить из системы вошедших в систему пользователей в PHP.

Источник

Оцените статью