- Ajax Login form using PHP and MySQL
- Create Ajax Login Form
- Login Form
- Database Details
- Config.php
- Login
- secure.php
- logout.php
- Регистрация на PHP, AJAX, MYSQL
- Архитектура проекта
- Форма регистрации
- Отправка формы
- Дополнительные файлы
- bootstrap.php
- db.php
- functions.php
- Registration Form using Ajax, PHP & MySQL
- Steps to Create Ajax Registration Form with PHP & MySQL
- 1. Create Registration Form Directory Structure
- 2. Create MySQL Table
- 3. Connect PHP to MySQL Database
- 4. Create a Registration Form UI
- Ajax Registration Form
- 5. Write ajax code for Registration
- 6. Write PHP to Insert Registration Data
- 7. Test Ajax Registration Form yourself
- Related posts:
Ajax Login form using PHP and MySQL
Today I would like to show you Ajax login functionality implementation using PHP and MySQL. We gonna use the MySQL PDO driver in this tutorial. PDO has a much nicer interface, you will end up being more productive, and write safer and cleaner code.
Create Ajax Login Form
Login Form
Create a file called login_form.php with the following code.
Login Page
Login Database Details
This tutorial assumes that you have the following user table structure in your database. For the sake of the example script, I have provided an insert query with test data.
CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `first_name`, `last_name`, `email`, `password`, `date_added`) VALUES (1, 'Arjun', 'PHP', '[email protected]', '$2y$10$8mVSGv/bIGgcvCikXBPfTu7HfXMl3jqfiirtQGyRwV5bvOzNGmmLG', '2017-10-12 18:09:10');
You can generate password hash by using password_hash() function, example echo password_hash(«password», PASSWORD_DEFAULT); .
Config.php
After importing the above table into your database. Create a file called config.php, where you gonna save information about MySQL Database configuration, you can use this file to save other config details too.
Login
Create a file called login.php with the following code. This file will handle the login requests, It will validate user details against the database. Upon valid and successful login, it will start the user session, otherwise, it will throw the appropriate error message.
if (empty($_POST['password'])) < $error[] = "Password field is required"; >if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) < $error[] = "Enter Valid Email address"; >if (count($error) > 0) < $resp['msg'] = $error; $resp['status'] = false; echo json_encode($resp); exit; >$statement = $db->prepare("select * from users where email = :email"); $statement->execute(array(':email' => $_POST['email'])); $row = $statement->fetchAll(PDO::FETCH_ASSOC); if (count($row) > 0) < if (!password_verify($_POST['password'], $row[0]['password'])) < $error[] = "Password is not valid"; $resp['msg'] = $error; $resp['status'] = false; echo json_encode($resp); exit; >session_start(); $_SESSION['user_id'] = $row[0]['user_id']; $resp['redirect'] = "dashboard.php"; $resp['status'] = true; echo json_encode($resp); exit; > else
secure.php
Create a file called secure.php file with the following code. On successful login, we will redirect the user to this page. Only authenticated users can access this page. If unauthorized users try to access this page, users will forcefully be redirected to the login page.
logout.php
Create a file called logout.php and put the below code in the file.
Once everything is in place head over to the browser with http://localhost/login_form.php you should get output something like the below image
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face — we are here to solve your problems.
Регистрация на PHP, AJAX, MYSQL
![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
Добрый день друзья, продолжаю небольшую серию уроков по PHP и AJAX, сегодня у нас написание простой системы регистрации пользователя. В данной статье мы будем использовать PHP, MySQL(PDO), JavaScript. Урок рассчитан на новичков, потому я не буду использовать ООП и сторонние пакеты, а наоборот покажу как на чистом PHP написать регистрацию. Для обработки формы регистрации мы будем использовать javascript, отправляя запрос на сервер и получая ответ. Давайте приступим.
Архитектура проекта
Архитектура проекта у нас очень простая. Мы имеем в корне index.php , это будет страница с формой регистрации, на ней же будем выводить список зарегистрированных пользователей. bootstrap.php — файл в корне, в который мы будем подключать файлы для работы с базой данных, наши функции и т.д., а он в свою очередь будет подключен в index.php .
Форма регистрации
В файл index.php вставим следующий код:
В этот файл мы подключаем библиотеку стилей bootstrap, а так же sweetalert — библиотека для красивых уведомлений и конечно же jQuery)
Отправка формы
Для отправки формы регистрации нам нужен javascript. Создадим папку assets/js и в ней файл form.js, вставляем следующий код в файл:
В скрипте мы при помощи jquery перехватываем отправку формы и выполняем POST запрос на handler.php , скрипт который обрабатывает данные с нашей формы. При успешной регистрации пользователя мы получим уведомление и страница будет перезагружена, при не успешной — форма будет подсвечена красным цветом.
Дополнительные файлы
bootstrap.php
Ничего особенного, место в котором стартует приложение и подключаются файлы с функциями и т.д.
db.php
Написал минимальное количество функций для работы текущего приложения.
function get_connection — подключение к базе данных.
function insert — вставка данных в таблицу.
function getUserByEmail — ищем пользователя по имейлу.
function getUsersList — получаем список пользователей.
functions.php
Файл в котором выполняем регистрацию пользователя и валидацию входных данных с формы.
В базе данных вам нужно выполнить запрос:
![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
Весь проект я сделал в докере и приложил файлы конфигурации, потому проблем с запуском быть не должно. После запуска проекта вы можете открыть в браузере http://localhost:8080 и должны увидеть страницу регистрации.
Если какие-то поля были заполнены не верно, вы получить вот такую форму
Registration Form using Ajax, PHP & MySQL
If you want to create a registration form that will not reload after submitting the registration details. Then you should make the ajax registration form with PHP & MySQL.
The Ajax Registration form is very useful to process the registered data quickly to the database without refreshing the web page. So. It is frequently used in most of web applications to make their registration form userfriendly & attractive.
In this tutorial, I have shared some simple steps to create the registration/signup form using jquery ajax in PHP & MySQL. Once you learn it you can create any type of other registration forms.
Steps to Create Ajax Registration Form with PHP & MySQL
Now, Let’s start the coding to create the ajax registration form with the following simple steps –
1. Create Registration Form Directory Structure
First of all, You should create the following directory structure to build the registration form.
source-code/ |__database.php |__ajax-script.php |__php-script.php |__index.php |
2. Create MySQL Table
Now, Create a MySQL Database –
Database Name – codingstatus
CREATE DATABASE codingstatus
After that create a table in the database ‘codingstatus’
CREATE TABLE `users` ( `id` int(10) NOT NULL AUTO_INCREMENT, `firstName` varchar(50) DEFAULT NOT NULL, `lastName` int(50) DEFAULT NOT NULL, `gender` int(10) DEFAULT NOT NULL, `emailAddress` int(50) DEFAULT NOT NULL, `password` int(20) DEFAULT NOT NULL );
3. Connect PHP to MySQL Database
Now, You have to connect PHP to the MySQL database with the following code
4. Create a Registration Form UI
To create the registration form UI, You have to follow the following points –
- Create a basic HTML structure
- Include the bootstrap5 CDN
- Create a form with id ‘registrationForm’
- Also, create some input fields for firstName, lastName, gender, email & submit button.
- Include the jQuery CDN
- Include the ajax-script.js
Ajax Registration Form