Необозримый register form php. Создаем невероятную простую систему регистрации на PHP и MySQL. Подключение к Базе Данных

Одно из главнейших достоинств PHP - то, как он работает с формами HTML. Здесь основным является то, что каждый элемент формы автоматически становится доступным вашим программам на PHP. Для подробной информации об использовании форм в PHP читайте раздел . Вот пример формы HTML:

Пример #1 Простейшая форма HTML

Ваше имя:

Ваш возраст:

В этой форме нет ничего особенного. Это обычная форма HTML без каких-либо специальных тегов. Когда пользователь заполнит форму и нажмет кнопку отправки, будет вызвана страница action.php . В этом файле может быть что-то вроде:

Пример #2 Выводим данные формы

Здравствуйте, .
Вам лет.

Пример вывода данной программы:

Здравствуйте, Сергей. Вам 30 лет.

Если не принимать во внимание куски кода с htmlspecialchars() и (int) , принцип работы данного кода должен быть прост и понятен. htmlspecialchars() обеспечивает правильную кодировку "особых" HTML-символов так, чтобы вредоносный HTML или Javascript не был вставлен на вашу страницу. Поле age, о котором нам известно, что оно должно быть число, мы можем просто преобразовать в integer , что автоматически избавит нас от нежелательных символов. PHP также может сделать это автоматически с помощью расширения filter . Переменные $_POST["name"] и $_POST["age"] автоматически установлены для вас средствами PHP. Ранее мы использовали суперглобальную переменную $_SERVER , здесь же мы точно так же используем суперглобальную переменную $_POST , которая содержит все POST-данные. Заметим, что метод отправки (method) нашей формы - POST. Если бы мы использовали метод GET , то информация нашей формы была бы в суперглобальной переменной $_GET . Кроме этого, можно использовать переменную $_REQUEST , если источник данных не имеет значения. Эта переменная содержит смесь данных GET, POST, COOKIE.

16 years ago

According to the HTTP specification, you should use the POST method when you"re using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it"s almost always an error -- you shouldn"t be posting the same comment twice -- which is why these pages aren"t bookmarked or cached.

You should use the GET method when your form is, well, getting something off the server and not actually changing anything. For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.

2 years ago

Worth clarifying:

POST is not more secure than GET.

The reasons for choosing GET vs POST involve various factors such as intent of the request (are you "submitting" information?), the size of the request (there are limits to how long a URL can be, and GET parameters are sent in the URL), and how easily you want the Action to be shareable -- Example, Google Searches are GET because it makes it easy to copy and share the search query with someone else simply by sharing the URL.

Security is only a consideration here due to the fact that a GET is easier to share than a POST. Example: you don"t want a password to be sent by GET, because the user might share the resulting URL and inadvertently expose their password.

However, a GET and a POST are equally easy to intercept by a well-placed malicious person if you don"t deploy TLS/SSL to protect the network connection itself.

All Forms sent over HTTP (usually port 80) are insecure, and today (2017), there aren"t many good reasons for a public website to not be using HTTPS (which is basically HTTP + Transport Layer Security).

As a bonus, if you use TLS you minimise the risk of your users getting code (ADs) injected into your traffic that wasn"t put there by you.

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

В большинстве случаев, применяют более упрощенную систему регистрации, которая написана на php в одном файле register.php .

Итак, мы немного отвлеклись, а сейчас рассмотрим более подробно файл регистрации.

Файл register.php

Для того, чтобы у вас это не отняло массу времени создадим систему, которая будет собирать пользователей, принимая от них минимальную контактную информацию. В данном случае все будем заносить в базу данных mysql. Для наибольшей скорости работы базы, будем создавать таблицу users в формате MyISAM и в кодировке utf-8.

Обратите внимание! Писать все скрипты нужно всегда в одной кодировке. Все файлы сайта и база данных MySql должны быть в единой кодировке. Самые распространенные кодировки UTF-8 и Windows-1251.

Для чего нужно писать все в одной кодировке мы поговорим как-нибудь попозже. А пока примите эту информацию как строжайшее правило создания скриптов иначе в будущем возникнут проблемы с работой скриптов. Ничего страшного, конечно, но просто потеряете массу времени для поиска ошибок в работе скрипта.

Как будет работать сам скрипт?

Мы хотим все упростить и получить быстрый результат. Поэтому будем получать от пользователей только логин, email и его пароль. А для защиты от спам-роботов, установим небольшую капчу. Иначе какой-нибудь мальчик из Лондона напишет небольшой робот-парсер, который заполнит всю базу липовыми пользователями за несколько минут, и будет радоваться своей гениальности и безнаказанности.

Вот сам скрипт. Все записано в одном файле register.php :

! `; // красный вопросительный знак $sha=$sh."scripts/pro/"; //путь к основной папке $bg=` bgcolor="#E1FFEB"`; // фоновый цвет строк?> Пример скрипта регистрации register.php style.css" />

В данном случае скрипт обращается к самому себе. И является формой и обработчиком данных занесенных в форму. Обращаю ваше внимание, что файл сжат zip-архивом и содержит файл конфигурации config.php, дамп базы данных users, файл содержащий вспомогательные функции functions.php, файл стилей style.css и сам файл register.php. Также несколько файлов, которые отвечают за работу и генерацию символов капчи.

В основном, для передачи параметров используются методы POST и GET .
Главное отличие методов POST и GET заключается в способе передачи информации. В методе GET параметры передаются через адресную строку (URL ), т.е. в HTTP -заголовке запроса, в то время как в методе POST параметры передаются через тело HTTP -запроса и никак не отражаются в адресной строке.

1. Кнопки – Тег

Тег обязателен.
Параметры:
disabled – блокирует доступ и изменение элемента.
type – тип кнопки
value – Значение кнопки, которое будет отправлено на сервер или прочитано с помощью сприптов.


Параметр DISABLED
Блокирует доступ и изменение кнопки. Она в таком случае отображается серой и недоступной для активации пользователем. Кроме того, такая кнопка не может получить фокус путем нажатия на клавишу Tab , мышью или другим способом. Тем не менее, такое состояние кнопки можно изменять через скрипты.

Параметр TYPE
Определяет тип кнопки, который устанавливает ее поведение в форме. По внешнему виду кнопки разного типа никак не различаются, но у каждой такой кнопки свои функции. Значение по умолчанию: button .
Аргументы:
button – Обычная кнопка.
reset – Кнопка для очистки введенных данных формы и возвращения значений в первоначальное состояние.

Submit – Кнопка для отправки данных формы на сервер.

Параметр VALUE Определяет значение кнопки, которое будет отправлено на сервер. На сервер отправляется пара «имя=значение », где имя задается параметром name тега

1.1. Кнопка (input type=button)
1.2. Кнопка с изображением (input type=image)

Кнопки с изображениями аналогичны по действию кнопке Submit , но представляют собой рисунок. Для этого задаем type=image и src="image.gif" .

Когда пользователь щелкнет где-нибудь на изображении, соответствующая форма будет передана на сервер с двумя дополнительными переменными – sub_x и sub_y . Они содержат координаты нажатия пользователя на изображение. Опытные программисты могут заметить, что на самом деле имена переменных, отправленных браузером, содержат точку, а не подчеркивание, но PHP автоматически конвертирует точку в подчеркивание.

1.3. Кнопка отправки формы (input type=submit)

Служит для отправки формы сценарию. При создании кнопки для отправки формы необходимо указать 2 атрибута: type="submit" и value="Текст кнопки" . Атрибут name необходим, если кнопка не одна, а несколько и все они созданы для разных операций, например кнопки "Сохранить", "Удалить", "Редактировать" и т.д. После нажатия на кнопку сценарию передается строка имя=текст кнопки.


РНР -сценарий не требуется.

1.4. Массив кнопок (submit) для выбора варианта действий
2. Кнопка сброса формы (Reset)

При нажатии на кнопку сброса (reset ), все элементы формы будут установлены в то состояние, которое было задано в атрибутах по умолчанию, причем отправка формы не производиться.


РНР -сценарий не требуется.

3. Флажок (checkbox)

Флажки checkbox предлагают пользователю ряд вариантов, и разрешает произвольный выбор (ни одного, одного или нескольких из них).

Белый
Зеленый
Синий
Красный
Черный
$go) { echo $index." - > ".$go."
"; }; };

4. Переключатель(radio)

Переключатели radio предлагают пользователю ряд вариантов, но разрешает выбрать только один из них.
Пример 1.

Белый
Зеленый
Синий
Красный
Черный

Пример 2.
// первый набор кнопок
// второй набор кнопок
// третий набор кнопок
\n"; ?>

5. Текстовое поле (text)

При создании обычного текстового поля размером size и максимальной допустимой длины maxlength символов, атрибут type принимает значение text . Если указан параметр value , то поле будет отображать указанный в переменной value. При создании поля не забывайте указывать имя поля, т.к. этот атрибут является обязательным.

6. Поле для ввода пароля (password)

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

7. Скрытое текстовое поле (hidden)

Позволяет передавать сценарию какую то служебную информацию, не отображая её на странице.

8. Выпадающий список (select)

Тэг . Теги позволяют определить содержимое списка, а параметр value определяет значение строки. Если в теге указан параметр selected , то строка будет изначально выбранной. Параметр size задает, сколько строк будет занимать список. Если size равен 1 , то список будет выпадающим. Если указан атрибут multiple , то разрешено выбирать несколько элементов из списка. Но эта схема практически не используется, а при size = 1 не имеет смысла.

Если необходимо создать выпадающий с предсказуемой последовательностью. Например, список с годами с 2000 по 2050. То используется следующий прием.

9. Многострочное поле ввода текста (textarea)

Многострочное поле ввода текста позволяет отправлять не одну строку, а сразу несколько. При необходимости можно указать атрибут readonly , который запрещает редактировать, удалять и изменять текст, т.е. текст будет предназначен только для чтения. Если необходимо чтобы текст был изначально отображен в многострочном поле ввода, то его необходимо поместить между тэгами .
Существует параметр wrap – задание переноса строк. Возможные значения:
off – отключает перенос строк;
virtuals – показывает переносы строк, но отправляет текст как он введен;
physical – переносы строк оставляются в исходном виде.
По умолчанию тег

Для того, чтобы в многострочном текстовом поле соблюдалось html-форматирование (перенос строк по средством тега
или
), то используйте функцию nl2br() :

10. Кнопка для загрузки файлов (browse)

Служит для реализации загрузки файлов на сервер. При создании текстового поля также необходимо указать тип поля type как "file" .

Загрузить файл:

Способы общения браузера с сервером

Способов, предоставляемых протоколом HTTP , немного. Это важная информация. Никаких других способов нет. На практике используются два:
GET – это когда данные передаются в адресной строке, например, когда пользователь жмет ссылку.
POST – когда он нажимает кнопку в форме.

Метод GET

Чтобы передать данные методом GET не надо создавать на HTML -странице форму (использовать формы для запросов методом GET вам никто не запрещает) – достаточно ссылки на документ с добавлением строки запроса, которая может выглядеть как переменная=значение. Пары объединяются с помощью амперсанда &, а к URL страницы строка присоединяется с помощью вопросительного знака «? ».
Но можно не использовать пары ключ=значение, если надо передать всего одну переменную – для этого надо после знака вопроса написать ЗНАЧЕНИЕ (не имя) переменной.
Преимущество передачи параметров таким способом заключается в том, что клиенты, которые не могут использовать метод POST (например, поисковые машины), все же смогут, просто пройдя по ссылке, передать параметры скрипту и получить содержимое.
Недостаток в том, что просто изменив параметры в адресной строке, пользователь может повернуть ход сценария непредсказуемым образом и это создает огромную дыру в безопасности, в сочетании с неопределенными переменными и register_globals on или кто-нибудь может узнать значение важной переменной (например ID -сеcсии), просто посмотрев на экран монитора.
:
- для доступа к общедоступным страницам с передачей параметров (повышение функциональности)
- передача информации, не влияющей на уровень безопасности
:
- для доступа к защищенным страницам с передачей параметров
- для передачи информации, влияющей на уровень безопасности
- для передачи информации, не подлежащей модифицированию пользователем (некоторые передают текст SQL -запросов.

Метод POST

Передать данные методом POST можно только с помощью формы на HTML странице. Основное отличие POST от GET в том, что данные передаются не в заголовке запроса а в теле, следовательно, пользователь их не видит. Модифицировать можно только изменив саму форму.
Преимущество :
- большая безопасность и функциональность запросов с помощью форм методом POST .
Недостаток :
- меньшая доступность.
Для чего следует использовать :
- для передачи большого объема информации (текст, файлы..);
- для передачи любой важной информации;
- для ограничения доступа (например, использовать для навигации только форму – возможность, доступная не всем программам-роботам или грабберам-контента).
Для чего не следует использовать :

PHP способен принимать файл, загружаемый при помощи любого браузера,. Это дает возможность загружать как текстовые, так и бинарные файлы. Вместе с PHP -аутентификацией и функциями для работы с файловой системой, вы получаете полный контроль над тем, кому разрешено загружать файлы, и над тем, что делать с файлом после его загрузки.
Страница для загрузки файлов может быть реализована при помощи специальной формы, которая выглядит примерно так:

//Форма для загрузки файлов

Отправить этот файл:

В приведенном выше примере "URL " необходимо заменить ссылкой на PHP -скрипт. Скрытое поле MAX _FILE_SIZE (значение необходимо указывать в байтах) должно предшествовать полю для выбора файла, и его значение является максимально допустимым размером принимаемого файла. Также следует убедиться, что в атрибутах формы вы указали enctype="multipart/form-data" , в противном случае загрузка файлов на сервер выполняться не будет.
Внимание
Опция MAX _FILE_SIZE является рекомендацией браузеру, даже если бы PHP также проверял это условие. Обойти это ограничение на стороне браузера достаточно просто, следовательно, вы не должны полагаться на то, что все файлы большего размера будут блокированы при помощи этой возможности. Тем не менее, ограничение PHP касательно максимального размера обойти невозможно. Вы в любом случае должны добавлять переменную формы MAX _FILE_SIZE , так как она предотвращает тревожное ожидание пользователей при передаче огромных файлов, только для того, чтобы узнать, что файл слишком большой и передача фактически не состоялась.

Как определить метод запроса?

Напрямую:

Getenv("REQUEST_METHOD");

вернет GET или POST .

Какой способ следует применять?

Если форма служит для запроса некой информации, например – при поиске, то ее следует отправлять методом GET . Чтобы можно было обновлять страницу, можно было поставить закладку и/или послать ссылку другу.
Если же в результате отправки формы данные записываются или изменяются на сервере, то следует их отправлять методом POST , причем обязательно, после обработки формы, надо перенаправить браузер методом GET . Так же, POST может понадобиться, если на сервер надо передать большой объём данных (у GET он сильно ограничен), а так же, если не следует "светить" передаваемые данные в адресной строке (при вводе логина и пароля, например).
В любом случае, после обработки POST надо всегда перенаправить браузер на какую-нибудь страницу, пусть ту же самую, но уже без данных формы, чтобы при обновлении страницы они не записывались повторно.

Как передать данные в другой файл непосредственно из тела PHP -программы методом GET и POST ?

Пример, для демонстрации отправки данных методом POST и GET одновременно и получения ответа от сервера.

In this tutorial, I walk you through the complete process of creating a user registration system where users can create an account by providing username, email and password, login and logout using PHP and MySQL. I will also show you how you can make some pages accessible only to logged-in users. Any other user not logged in will not be able to access the page.

Learn how to create a complete blog with PHP and MySQL database with my free course on YouTube .

The first thing we"ll need to do is set up our database.

Create a database called registration . In the registration database, add a table called users . The users table will take the following four fields.

  • username - varchar(100)
  • email - varchar(100)
  • password - varchar(100)

You can create this using a MySQL client like PHPMyAdmin.

Or you can create it on the MySQL prompt using the following SQL script:

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

And that"s it with the database.

Now create a folder called registration in a directory accessible to our server. i.e create the folder inside htdocs (if you are using XAMPP server) or inside www (if you are using wampp server).

Inside the folder registration, create the following files:

Open these files up in a text editor of your choice. Mine is Sublime Text 3.

Registering a user

Open the register.php file and paste the following code in it:

regiser.php:

Register

Already a member? Sign in

Nothing complicated so far right?

A few things to note here:

First is that our form"s action attribute is set to register.php. This means that when the form submit button is clicked, all the data in the form will be submitted to the same page (register.php). The part of the code that receives this form data is written in the server.php file and that"s why we are including it at the very top of the register.php file.

Notice also that we are including the errors.php file to display form errors. We will come to that soon.

As you can see in the head section, we are linking to a style.css file. Open up the style.css file and paste the following CSS in it:

* { margin: 0px; padding: 0px; } body { font-size: 120%; background: #F8F8FF; } .header { width: 30%; margin: 50px auto 0px; color: white; background: #5F9EA0; text-align: center; border: 1px solid #B0C4DE; border-bottom: none; border-radius: 10px 10px 0px 0px; padding: 20px; } form, .content { width: 30%; margin: 0px auto; padding: 20px; border: 1px solid #B0C4DE; background: white; border-radius: 0px 0px 10px 10px; } .input-group { margin: 10px 0px 10px 0px; } .input-group label { display: block; text-align: left; margin: 3px; } .input-group input { height: 30px; width: 93%; padding: 5px 10px; font-size: 16px; border-radius: 5px; border: 1px solid gray; } .btn { padding: 10px; font-size: 15px; color: white; background: #5F9EA0; border: none; border-radius: 5px; } .error { width: 92%; margin: 0px auto; padding: 10px; border: 1px solid #a94442; color: #a94442; background: #f2dede; border-radius: 5px; text-align: left; } .success { color: #3c763d; background: #dff0d8; border: 1px solid #3c763d; margin-bottom: 20px; }

Now the form looks beautiful.

Let"s now write the code that will receive information submitted from the form and store (register) the information in the database. As promised earlier, we do this in the server.php file.

Open server.php and paste this code in it:

server.php

Sessions are used to track logged in users and so we include a session_start() at the top of the file.

The comments in the code pretty much explain everything, but I"ll highlight a few things here.

The if statement determines if the reg_user button on the registration form is clicked. Remember, in our form, the submit button has a name attribute set to reg_user and that is what we are referencing in the if statement.

All the data is received from the form and checked to make sure that the user correctly filled the form. Passwords are also compared to make sure they match.

If no errors were encountered, the user is registered in the users table in the database with a hashed password. The hashed password is for security reasons. It ensures that even if a hacker manages to gain access to your database, they would not be able to read your password.

But error messages are not displaying now because our errors.php file is still empty. To display the errors, paste this code in the errors.php file.

0) : ?>

When a user is registered in the database, they are immediately logged in and redirected to the index.php page.

And that"s it for registration. Let"s look at user login.

Login user

Logging a user in is an even easier thing to do. Just open the login page and put this code inside it:

Registration system PHP and MySQL

Login

Not yet a member? Sign up

Everything on this page is quite similar to the register.php page.

Now the code that logs the user in is to be written in the same server.php file. So open the server.php file and add this code at the end of the file:

// ... // LOGIN USER if (isset($_POST["login_user"])) { $username = mysqli_real_escape_string($db, $_POST["username"]); $password = mysqli_real_escape_string($db, $_POST["password"]); if (empty($username)) { array_push($errors, "Username is required"); } if (empty($password)) { array_push($errors, "Password is required"); } if (count($errors) == 0) { $password = md5($password); $query = "SELECT * FROM users WHERE username="$username" AND password="$password""; $results = mysqli_query($db, $query); if (mysqli_num_rows($results) == 1) { $_SESSION["username"] = $username; $_SESSION["success"] = "You are now logged in"; header("location: index.php"); }else { array_push($errors, "Wrong username/password combination"); } } } ?>

Again all this does is check if the user has filled the form correctly, verifies that their credentials match a record from the database and logs them in if it does. After logging in, the user is redirected them to the index.php file with a success message.

Now let"s see what happens in the index.php file. Open it up and paste the following code in it:

Home

Home Page

Welcome

logout

The first if statement checks if the user is already logged in. If they are not logged in, they will be redirected to the login page. Hence this page is accessible to only logged in users. If you"d like to make any page accessible only to logged in users, all you have to do is place this if statement at the top of the file.

The second if statement checks if the user has clicked the logout button. If yes, the system logs them out and redirects them back to the login page.

Now go on, customize it to suit your needs and build an awesome site. If you have any worries or anything you need to clarify, leave it in the comments below and help will come.

You can always support by sharing on social media or recommending my blog to your friends and colleagues.

Last modified on July 23rd, 2019 by Vincy.

User registration or sign up is an integral part of many web applications and it is critical to get it right for the success of the application. It is the starting point of user engagement with your application.

It should be as simple as possible with best UI / UX. Implementing user registration functionality using PHP is a simple task and I will walk you through the steps with example in this article.

What is inside?

How this PHP user registration example works?

This example code can be separated into 3 parts.

  1. Getting user information via a HTML form.
  2. Validating user submitted information on form submit.
  3. Database handling to save registered user to the database after validation.

The third step will be executed after ensuring that the user is not added already. This data uniqueness validation will be performed based on their email and username entered by them.

During registration we generally collect user information, who are ready to register with our application. Some of them will be mandatory and some of them will be optional.

So, this functionality may also include validation part to ensure about the non-emptiness and the format of the user data. The validation could be done either in client-side or server side.

Having validation at server-side is always better. You can choose to have it in client-side also for the ease of use of the users. But having at the server-side is not optional and a minimum requirement.

File structure

HTML form to allow user to register

In this example, the registration form contains the fields Username, Name(Display Name), Password and Email. It also has the Confirm Password field to let the user to reenter his password for the confirmation. These two passwords will be compared later at the time of a .

By submitting this form, the user is expected to agree the terms and conditions. So a checkbox field is added before the Register button for ensuring it.

PHP User Registration Form

Sign Up
"; } ?>
">
">
">
I accept terms and conditions

And the styles are,

Body { font-family: Arial; color: #333; font-size: 0.95em; } .form-head { color: #191919; font-weight: normal; font-weight: 400; margin: 0; text-align: center; font-size: 1.8em; } .error-message { padding: 7px 10px; background: #fff1f2; border: #ffd5da 1px solid; color: #d6001c; border-radius: 4px; margin: 30px 0px 10px 0px; } .success-message { padding: 7px 10px; background: #cae0c4; border: #c3d0b5 1px solid; color: #027506; border-radius: 4px; margin: 30px 0px 10px 0px; } .demo-table { background: #ffffff; border-spacing: initial; margin: 15px auto; word-break: break-word; table-layout: auto; line-height: 1.8em; color: #333; border-radius: 4px; padding: 20px 40px; width: 380px; border: 1px solid; border-color: #e5e6e9 #dfe0e4 #d0d1d5; } .demo-table .label { color: #888888; } .demo-table .field-column { padding: 15px 0px; } .demo-input-box { padding: 13px; border: #CCC 1px solid; border-radius: 4px; width: 100%; } .btnRegister { padding: 13px; background-color: #5d9cec; color: #f5f7fa; cursor: pointer; border-radius: 4px; width: 100%; border: #5791da 1px solid; font-size: 1.1em; } .response-text { max-width: 380px; font-size: 1.5em; text-align: center; background: #fff3de; padding: 42px; border-radius: 3px; border: #f5e9d4 1px solid; font-family: arial; line-height: 34px; margin: 15px auto; } .terms { margin-bottom: 5px; }

How to validate user information on form submit

A server-side form validation script is added in this example for validating the user registration data. This PHP validation script will be called on submitting the registration form.

This script validates all form fields to check the non-emptiness for each field. Then it validates the user email format using PHP filter_var() function.

As the registration includes password confirmation feature, the password comparison will take place at this part of this example.

Finally, the validation script will check if the user accepts term and condition by checking the appropriate box on the form.

Once all the validation completed by returning boolean true, then the actual registration process will take place.

Function validateMember() { $valid = true; $errorMessage = array(); foreach ($_POST as $key => $value) { if (empty($_POST[$key])) { $valid = false; } } if($valid == true) { if ($_POST["password"] != $_POST["confirm_password"]) { $errorMessage = "Passwords should be same."; $valid = false; } if (! isset($error_message)) { if (! filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) { $errorMessage = "Invalid email address."; $valid = false; } } if (! isset($error_message)) { if (! isset($_POST["terms"])) { $errorMessage = "Accept terms and conditions."; $valid = false; } } } else { $errorMessage = "All fields are required."; } if ($valid == false) { return $errorMessage; } return; }

PHP MySQL code to access database to save registered user

Server-side user form validation

This is the PHP entry point to handle all the server-side script to validate form and to handle database operations based on the validation result.

validateMember($username, $displayName, $password, $email); if (empty($errorMessage)) { $memberCount = $member->isMemberExists($username, $email); if ($memberCount == 0) { $insertId = $member->insertMemberRecord($username, $displayName, $password, $email); if (! empty($insertId)) { header("Location: thankyou.php"); } } else { $errorMessage = "User already exists."; } } } ?>

Check if user already exists

The isMemberExists() function is used to check the user data uniqueness based on their email and the username. If the entered username or email there exists in the user database, then the registration process will be stopped by returning and acknowledgement.

This acknowledgement will notify that the “user already exists”. The code is,

Function isMemberExists($username, $email) { $query = "select * FROM registered_users WHERE user_name = ? OR email = ?"; $paramType = "ss"; $paramArray = array($username, $email); $memberCount = $this->ds->numRows($query, $paramType, $paramArray); return $memberCount; }

Insert member data to the database

If it returns 0 then it means that there is no such users exist with the email or the username entered. And so, the registration data will be inserted to the database. The following code shows the member insert method.

Function insertMemberRecord($username, $displayName, $password, $email) { $passwordHash = md5($password); $query = "INSERT INTO registered_users (user_name, display_name, password, email) VALUES (?, ?, ?, ?)"; $paramType = "ssss"; $paramArray = array($username, $displayName, $passwordHash, $email); $insertId = $this->ds->insert($query, $paramType, $paramArray); return $insertId; }

DataSource.php

This is the generic data source class in PHP to perform database operations. It includes functions to connect database and execute various queries to get database result, row count, execute insert and more.

This datasource class is generic and kept as simple as possible. It is efficient and I use it in my most of the micro projects and tutorials. You are free to download and use it.

Important thing is never forget to use the Prepared Statements . It helps you to safeguard from SQL injection attacks and it is the first step in terms of implementing security in a web application.

conn = $this->getConnection(); } /** * If connection object is needed use this method and get access to it. * Otherwise, use the below methods for insert / update / etc. * * @return \mysqli */ public function getConnection() { $conn = new \mysqli(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASENAME); if (mysqli_connect_errno()) { trigger_error("Problem with connecting to database."); } $conn->set_charset("utf8"); return $conn; } /** * To get database results * @param string $query * @param string $paramType * @param array $paramArray * @return array */ public function select($query, $paramType="", $paramArray=array()) { $stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) { $this->bindQueryParams($sql, $paramType, $paramArray); } $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $resultset = $row; } } if (! empty($resultset)) { return $resultset; } } /** * To insert * @param string $query * @param string $paramType * @param array $paramArray * @return int */ public function insert($query, $paramType, $paramArray) { print $query; $stmt = $this->conn->prepare($query); $this->bindQueryParams($stmt, $paramType, $paramArray); $stmt->execute(); $insertId = $stmt->insert_id; return $insertId; } /** * To execute query * @param string $query * @param string $paramType * @param array $paramArray */ public function execute($query, $paramType="", $paramArray=array()) { $stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) { $this->bindQueryParams($stmt, $paramType="", $paramArray=array()); } $stmt->execute(); } /** * 1. Prepares parameter binding * 2. Bind prameters to the sql statement * @param string $stmt * @param string $paramType * @param array $paramArray */ public function bindQueryParams($stmt, $paramType, $paramArray=array()) { $paramValueReference = & $paramType; for ($i = 0; $i < count($paramArray); $i ++) { $paramValueReference = & $paramArray[$i]; } call_user_func_array(array($stmt, "bind_param"), $paramValueReference); } /** * To get database results * @param string $query * @param string $paramType * @param array $paramArray * @return array */ public function numRows($query, $paramType="", $paramArray=array()) { $stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) { $this->bindQueryParams($stmt, $paramType, $paramArray); } $stmt->execute(); $stmt->store_result(); $recordCount = $stmt->num_rows; return $recordCount; } }

Database script

This database script has the create statement for the registered_users table. Import this script in your development environment to run this code.

Table structure for table `registered_users` -- CREATE TABLE IF NOT EXISTS `registered_users` (`id` int(8) NOT NULL AUTO_INCREMENT, `user_name` varchar(255) NOT NULL, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `password` varchar(25) NOT NULL, `email` varchar(55) NOT NULL, `gender` varchar(20) NOT NULL, PRIMARY KEY (`id`));

If the registration form validation fails, then the error message will be shown to the user as like as below.

Comments to “PHP User Registration Form (Sign up) with MySQL Database”

    Hi Vincy, I get the following errors when running the register code, please help.

    INSERT INTO registered_users (user_name, display_name, password, email) VALUES (?, ?, ?, ?)
    Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php on line 136

    Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php:99 Stack trace: #0 C:\xampp\htdocs\PHP\JAMII-CASH\Member.php(83): Phppot\DataSource->insert(‘INSERT INTO reg…’, ‘ssss’, Array) #1 C:\xampp\htdocs\PHP\JAMII-CASH\index.php(20): Phppot\Member->insertMemberRecord(‘chuki10’, ‘Ray’, ‘202020’, ‘raf.yah.s.1@gma…’) #2 {main} thrown in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php on line 99

  • Сергей Савенков

    какой то “куцый” обзор… как будто спешили куда то