Дикарь register form php. Создаем невероятную простую систему регистрации на PHP и MySQL. Как пользоваться этой системой

What is Form?

When you login into a website or into your mail box, you are interacting with a form.

Forms are used to get input from the user and submit it to the web server for processing.

The diagram below illustrates the form handling process.

A form is an HTML tag that contains graphical user interface items such as input box, check boxes radio buttons etc.

The form is defined using the ... tags and GUI items are defined using form elements such as input.

In this tutorial, you will learn-

When and why we are using forms?
  • Forms come in handy when developing flexible and dynamic applications that accept user input.
  • Forms can be used to edit already existing data from the database
Create a form

We will use HTML tags to create a form. Below is the minimal list of things you need to create a form.

  • Opening and closing form tags …
  • Form submission type POST or GET
  • Submission URL that will process the submitted data
  • Input fields such as input boxes, text areas, buttons,checkboxes etc.

The code below creates a simple registration form

Registration Form Registration Form First name:
Last name:

Viewing the above code in a web browser displays the following form.


  • … are the opening and closing form tags
  • action="registration_form.php" method="POST"> specifies the destination URL and the submission type.
  • First/Last name: are labels for the input boxes
  • are input box tags

  • is the new line tag
  • is a hidden value that is used to check whether the form has been submitted or not
  • is the button that when clicked submits the form to the server for processing
Submitting the form data to the server

The action attribute of the form specifies the submission URL that processes the data. The method attribute specifies the submission type.

PHP POST method
  • This is the built in PHP super global array variable that is used to get values submitted via HTTP POST method.
  • This method is ideal when you do not want to display the form post values in the URL.
  • A good example of using post method is when submitting login details to the server.

It has the following syntax.

  • “$_POST[…]” is the PHP array
PHP GET method
  • This is the built in PHP super global array variable that is used to get values submitted via HTTP GET method.
  • The array variable can be accessed from any script in the program; it has a global scope.
  • This method displays the form values in the URL.
  • It’s ideal for search engine forms as it allows the users to book mark the results.

It has the following syntax.

  • “$_GET[…]” is the PHP array
  • “"variable_name"” is the URL variable name.
GET vs POST Methods POST GET
Values not visible in the URL Values visible in the URL
Has not limitation of the length of the values since they are submitted via the body of HTTP Has limitation on the length of the values usually 255 characters. This is because the values are displayed in the URL. Note the upper limit of the characters is dependent on the browser.
Has lower performance compared to Php_GET method due to time spent encapsulation the Php_POST values in the HTTP body Has high performance compared to POST method dues to the simple nature of appending the values in the URL.
Supports many different data types such as string, numeric, binary etc. Supports only string data types because the values are displayed in the URL
Results cannot be book marked Results can be book marked due to the visibility of the values in the URL

The below diagram shows the difference between get and post



Processing the registration form data

The registration form submits data to itself as specified in the action attribute of the form.

When a form has been submitted, the values are populated in the $_POST super global array.

We will use the PHP isset function to check if the form values have been filled in the $_POST array and process the data.

We will modify the registration form to include the PHP code that processes the data. Below is the modified code

Registration Form //this code is executed when the form is submitted Thank You

You have been registered as

Go back to the form

Registration Form First name:
Last name: checks if the form_submitted hidden field has been filled in the $_POST array and display a thank you and first name message.

If the form_fobmitted field hasn’t been filled in the $_POST array, the form is displayed.

More examples Simple search engine

We will design a simple search engine that uses the PHP_GET method as the form submission type.

For simplicity’s sake, we will use a PHP If statement to determine the output.

We will use the same HTML code for the registration form above and make minimal modifications to it.

Simple Search Engine Search Results For

The GET method displays its values in the URL

Sorry, no matches found for your search term

Go back to the form

Simple Search Engine - Type in GET Search Term:

View the above page in a web browser

The following form will be shown

Type GET in upper case letter then click on submit button.

The following will be shown

The diagram below shows the URL for the above results

Note the URL has displayed the value of search_term and form_submitted. Try to enter anything different from GET then click on submit button and see what results you will get.

Working with check boxes, radio buttons

If the user does not select a check box or radio button, no value is submitted, if the user selects a check box or radio button, the value one (1) or true is submitted.

We will modify the registration form code and include a check button that allows the user to agree to the terms of service.

Registration Form

You have not accepted our terms of service

Thank You

You have been registered as

Go back to the form

Registration Form First name:
Last name:
Agree to Terms of Service:

View the above form in a browser


Back in March of this year, I had a very bad experience with a media company refusing to pay me and answer my emails. They still owe me thousands of dollars and the feeling of rage I have permeates everyday. Turns out I am not alone though, and hundreds of other website owners are in the same boat. It"s sort of par for the course with digital advertising.

In all honesty, I"ve had this blog for a long time and I have bounced around different ad networks in the past. After removing the ad units from that company who stiffed me, I was back to square one. I should also note that I never quite liked Googles AdSense product, only because it feels like the "bottom of the barrel" of display ads. Not from a quality perspective, but from a revenue one.

From what I understand, you want Google advertising on your site, but you also want other big companies and agencies doing it as well. That way you maximize the demand and revenue.

After my negative experience I got recommend a company called Newor Media . And if I"m honest I wasn"t sold at first mostly because I couldn"t find much information on them. I did find a couple decent reviews on other sites, and after talking to someone there, I decided to give it a try. I will say that they are SUPER helpful. Every network I have ever worked with has been pretty short with me in terms of answers and getting going. They answered every question and it was a really encouraging process.

I"ve been running the ads for a few months and the earnings are about in line with what I was making with the other company. So I can"t really say if they are that much better than others, but where they do stand out is a point that I really want to make. The communication with them is unlike any other network I"ve ever worked it. Here is a case where they really are different:

They pushed the first payment to me on time with Paypal. But because I"m not in the U.S (and this happens for everyone I think), I got a fee taken out from Paypal. I emailed my representative about it, asking if there was a way to avoid that in the future.

They said that they couldn"t avoid the fee, but that they would REIMBURSE ALL FEES.... INCLUDING THE MOST RECENT PAYMENT! Not only that, but the reimbursement payment was received within 10 MINUTES! When have you ever been able to make a request like that without having to be forwarded to the "finance department" to then never be responded to.

The bottom line is that I love this company. I might be able to make more somewhere else, I"m not really sure, but they have a publisher for life with me. I"m not a huge site and I don"t generate a ton of income, but I feel like a very important client when I talk to them. It"s genuinely a breathe of fresh air in an industry that is ripe with fraud and non-responsiveness.

Microcomputers that have been created by the Raspberry Pi Foundation in 2012 have been hugely successful in sparking levels of creativity in young children and this UK based company began offering learn-to-code startup programs like pi-top an Kano. There is now a new startup that is making use of Pi electronics, and the device is known as Pip, a handheld console that offers a touchscreen, multiple ports, control buttons and speakers. The idea behind the device is to engage younger individuals with a game device that is retro but will also offer a code learning experience through a web based platform.

The amazing software platform being offered with Pip will offer the chance to begin coding in Python, HTML/CSS, JavaScript, Lua and PHP. The device offers step-by-step tutorials to get children started with coding and allows them to even make LEDs flash. While Pip is still a prototype, it will surely be a huge hit in the industry and will engage children who have an interest in coding and will provide them the education and resources needed to begin coding at a young age.

Future of Coding Coding has a great future, and even if children will not be using coding as a career, they can benefit from learning how to code with this new device that makes it easier than ever. With Pip, even the youngest coding enthusiasts will learn different languages and will be well on their way to creating their own codes, own games, own apps and more. It is the future of the electronic era and Pip allows the basic building blocks of coding to be mastered.
Computer science has become an important part of education and with devices like the new Pip , children can start to enhance their education at home while having fun. Coding goes far beyond simply creating websites or software. It can be used to enhance safety in a city, to help with research in the medical field and much more. Since we now live in a world that is dominated by software, coding is the future and it is important for all children to at least have a basic understanding of how it works, even if they never make use of these skills as a career. In terms of the future, coding will be a critical component of daily life. It will be the language of the world and not knowing computers or how they work can pose challenges that are just as difficult to overcome as illiteracy.
Coding will also provide major changes in the gaming world, especially when it comes to online gaming, including the access of online casinos. To see just how coding has already enhanced the gaming world, take a look at a few top rated casino sites that rely on coding. Take a quick peek to check it out and see just how coding can present realistic environments online.How Pip Engages Children When it comes to the opportunity to learn coding, children have many options. There are a number of devices and hardware gizmos that can be purchased, but Pip takes a different approach with their device. The portability of the device and the touchscreen offer an advantage to other coding devices that are on the market. Pip will be fully compatible with electronic components in addition to the Raspberry Pi HAT system. The device uses standard languages and has basic tools and is a perfect device for any beginner coder. The goal is to remove any barriers between an idea and creation and make tools immediately available for use. One of the other great advantages of Pip is that it uses a SD card, so it can be used as a desktop computer as well when it is connected to a monitor and mouse.
The Pip device would help kids and interested coder novice with an enthusiasm into learning and practicing coding. By offering a combination of task completion and tinkering to solve problems, the device will certainly engage the younger generation. The device then allows these young coders to move to more advanced levels of coding in different languages like JavaScript and HTML/CSS. Since the device replicates a gaming console, it will immediately capture the attention of children and will engage them to learn about coding at a young age. It also comes with some preloaded games to retain attention, such as Pac-Man and Minecraft. Innovations to Come Future innovation largely depends on a child’s current ability to code and their overall understanding of the process. As children learn to code at an early age by using such devices as the new Pip, they will gain the skills and knowledge to create amazing things in the future. This could be the introduction of new games or apps or even ideas that can come to life to help with medical research and treatments. There are endless possibilities. Since our future will be controlled by software and computers, starting young is the best way to go, which is why the new Pip is geared towards the young crowd. By offering a console device that can play games while teaching coding skills, young members of society are well on their way to being the creators of software in the future that will change all our lives. This is just the beginning, but it is something that millions of children all over the world are starting to learn and master. With the use of devices like Pip, coding basics are covered and children will quickly learn the different coding languages that can lead down amazing paths as they enter adulthood.

Hello friends, Today in this tutorial we will see How to design Login, Signup & Forgot Password Modal Forms using Bootstrap . Creating and customizing these bootstrap modals are quite easy, i mean literally easy, Modals allow you to open excellent pop-up windows within the same page without redirecting to any separate pages for any particular task, E.g Separate Login/Signup pages, Having Modal Forms on website gives better UI. In this example i have covered login, signup and forgot password modals which you can create easily, let"s take a look.

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

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

Тег создает на веб-странице кнопки и по своему действию напоминает результат, получаемый с помощью тега (с параметром type="button | reset | submit" ). В отличие от этого тега, предлагает расширенные возможности по созданию кнопок. Например, на подобной кнопке можно размещать любые элементы HTML , в том числе изображения. Используя стили, можно определить вид кнопки путем изменения шрифта, цвета фона, размеров и других параметров.
Теоретически, тег должен располагаться внутри формы, устанавливаемой элементом . Тем не менее, браузеры не выводят сообщение об ошибке и корректно работают с тегом , если он встречается самостоятельно. Однако, если необходимо результат нажатия на кнопку отправить на сервер, помещать в контейнер обязательно. Закрывающий тег обязателен.
Параметры:
disabled – блокирует доступ и изменение элемента.
type – тип кнопки
value – Значение кнопки, которое будет отправлено на сервер или прочитано с помощью сприптов.

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

Активная кнопка Неактивная кнопка

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

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

Очистить форму Отправить форму

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

Отправить форму

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 предлагают пользователю ряд вариантов, и разрешает произвольный выбор (ни одного, одного или нескольких из них).

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

Пример 2.
// первый набор кнопок
// второй набор кнопок
// третий набор кнопок

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 – переносы строк оставляются в исходном виде.
По умолчанию тег создает пустое поле шириной в 20 символов и состоящее из 2 строк.


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

Первоначально вставленный строка 1 Первоначально вставленный строка 2 Первоначально вставленный строка 3

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 одновременно и получения ответа от сервера.

Последнее обновление: 1.11.2015

Одним из основных способов передачи данных веб-сайту является обработка форм. Формы представляют специальные элементы разметки HTML, которые содержат в себе различные элементы ввода - текстовые поля, кнопки и т.д. И с помощью данных форм мы можем ввести некоторые данные и отправить их на сервер. А сервер уже обрабатывает эти данные.

Создание форм состоит из следующих аспектов:

    Создание элемента в разметке HTML

    Добавление в этот элемент одно или несколько поле ввода

    Установка метода передачи данных: GET или POST

    Установка адреса, на который будут отправляться введенные данные

Итак, создадим новую форму. Для этого определим новый файл form.php , в которое поместим следующее содержимое:

Вход на сайт Логин:

Пароль:

Атрибут action="login.php" элемента form указывает, что данные формы будет обрабатывать скрипт login.php , который будет находиться с файлом form.php в одной папке. А атрибут method="POST" указывает, что в качестве метода передачи данных будет применяться метод POST.

Теперь создадим файл login.php , который будет иметь следующее содержание:

Чтобы получить данные формы, используется глобальная переменная $_POST . Она представляет ассоциативный массив данных, переданных с помощью метода POST. Используя ключи, мы можем получить отправленные значения. Ключами в этом массиве являются значения атрибутов name у полей ввода формы.

Так как атрибут name поля ввода логина имеет значение login (), то в массиве $_POST значение этого поля будет представлять ключ "login": $_POST["login"]

И поскольку возможны ситуации, когда поле ввода будет не установлено, например, при прямом переходе к скрипту: http://localhost:8080/login.php . В этом случае желательно перед обработкой данных проверять их наличие с помощью функции isset() . И если переменная установлена, то функция isset() возвратит значение true .

Теперь мы можем обратиться к форме:

И по нажатию кнопки введенные данные методом POST будут отправлены скрипту login.php :

Необязательно отправлять данные формы другому скрипту, можно данные формы обработать в том же файле формы. Для этого изменим файл form.php следующим образом:

Вход на сайт Логин:

Пароль:

Безопасность данных

Большое значение в PHP имеет организация безопасности данных. Рассмотрим несколько простых механизмов, которые могут повысить безопасность нашего веб-сайта.

Но вначале возьмем форму из прошлой темы и попробуем ввести в нее некоторые данные. Например, введем в поле для логина "alert(hi);", а в поле для пароля текст "пароль":

После отправки данных в html разметку будет внедрен код javascript, который выводит окно с сообщением.

Чтобы избежать подобных проблем с безопасностью, следует применять функцию htmlentities() :

If(isset($_POST["login"]) && isset($_POST["password"])){ $login=htmlentities($_POST["login"]); $password = htmlentities($_POST["password"]); echo "Ваш логин: $login
Ваш пароль: $password"; }

И даже после ввода кода html или javascript все теги будут экранированы, и мы получим следующий вывод:

Еще одна функция - функция strip_tags() позволяет полностью исключить теги html:

If(isset($_POST["login"]) && isset($_POST["password"])){ $login=strip_tags($_POST["login"]); $password = strip_tags($_POST["password"]); echo "Ваш логин: $login
Ваш пароль: $password"; }

Результатом ее работы при том же вводе будет следующий вывод.

Much of the websites have a registration form for your users to sign up and thus may benefit from some kind of privilege within the site. In this article we will see how to create a registration form in PHP and MySQL.

We will use simple tags and also we will use table tag to design the Sign-Up.html webpage. Let’s start:

Listing 1 : sign-up.html

Sign-Up Registration Form

Name
Email
UserName
Password
Confirm Password


Figure 1:

Description of sing-in.html webpage:

As you can see the Figure 1, there is a Registration form and it is asking few data about user. These are the common data which ask by any website from his users or visitors to create and ID and Password. We used table tag because to show the form fields on the webpage in a arrange form as you can see them on Figure 1. It’s looking so simple because we yet didn’t used CSS Style on it now let’s we use CSS styles and link the CSS style file with sing-up.html webpage.

Listing 2 : style.css

/*CSS File For Sign-Up webpage*/ #body-color{ background-color:#6699CC; } #Sign-Up{ background-image:url("sign-up.png"); background-size:500px 500px; background-repeat:no-repeat; background-attachment:fixed; background-position:center; margin-top:150px; margin-bottom:150px; margin-right:150px; margin-left:450px; padding:9px 35px; } #button{ border-radius:10px; width:100px; height:40px; background:#FF00FF; font-weight:bold; font-size:20px; }

Listing 3 : Link style.css with sign-up.html webpage



Figure 2:

Description of style.css file:

In the external CSS file we used some styles which could be look new for you. As we used an image in the background and set it in the center of the webpage. Which is become easy to use by the help of html div tag. As we used three div tag id’s. #button, #sing-up, and #body-color and we applied all CSS styles on them and now you can see the Figure 2, how much it’s looking beautiful and attractive. You can use many other CSS styles as like 2D and 3D CSS styles on it. It will look more beautiful than its looking now.

After these all simple works we are now going to create a database and a table to store all data in the database of new users. Before we go to create a table we should know that what we require from the user. As we designed the form we will create the table according to the registration form which you can see it on Figure 1 & 2.

Listing 3 : Query for table in MySQL

CREATE TABLE WebsiteUsers (userID int(9) NOT NULL auto_increment, fullname VARCHAR(50) NOT NULL, userName VARCHAR(40) NOT NULL, email VARCHAR(40) NOT NULL, pass VARCHAR(40) NOT NULL, PRIMARY KEY(userID));

Description of Listing 3:

One thing you should know that if you don’t have MySQL facility to use this query, so should follow my previous article about . from this link you will able to understand the installation and requirements. And how we can use it.

In the listing 3 query we used all those things which we need for the registration form. As there is Email, Full name, password, and user name variables. These variable will store data of the user, which he/she will input in the registration form in Figure 2 for the sing-up.

After these all works we are going to work with PHP programming which is a server side programming language. That’s why need to create a connection with the database.

Listing 4 : Database connection

Description of Listing 4:

We created a connection between the database and our webpages. But if you don’t know is it working or not so you use one thing more in the last check listing 5 for it.

Listing 5 : checking the connection of database connectivity

Description Listing 5:

In the Listing 5 I just tried to show you that you can check and confirm the connection between the database and PHP. And one thing more we will not use Listing 5 code in our sing-up webpage. Because it’s just to make you understand how you can check the MySQL connection.

Now we will write a PHP programming application to first check the availability of user and then store the user if he/she is a new user on the webpage.

Listing 6 : connectivity-sign-up.php

Description of connectivity-sign-up.php

In this PHP application I used simplest way to create a sign up application for the webpages. As you can see first we create a connection like listing 4. And then we used two functions the first function is SignUP() which is being called by the if statement from the last of the application, where its first confirming the pressing of sign up button. If it is pressed then it will call the SingUp function and this function will use a query of SELECT to fetch the data and compare them with userName and email which is currently entered from the user. If the userName and email is already present in the database so it will say sorry you are already registered

If the user is new as its currently userName and email ID is not present in the database so the If statement will call the NewUser() where it will store the all information of the new user. And the user will become a part of the webpage.



Figure 3

In the figure 3, user is entering data to sign up if the user is an old user of this webpage according to the database records. So the webpage will show a message the user is registered already if the user is new so the webpage will show a message the user’s registration is completed.



Figure 4:

As we entered data to the registration form (Figure 4), according to the database which userName and email we entered to the registration form for sing-up it’s already present in the database. So we should try a new userName and email address to sign-up with a new ID and Password.



Figure 5

In figure 5, it is confirming us that which userName and email id user has entered. Both are not present in the database records. So now a new ID and Password is created and the user is able to use his new ID and Password to get login next time.

Conclusion:

In this article we learnt the simplest way of creating a sign up webpage. We also learnt that how it deals with the database if we use PHP and MySQL. I tried to give you a basic knowledge about sign up webpage functionality. How it works at back end, and how we can change its look on front end. For any query don’t hesitate and comment.