목차
Creating a MySQL database and table
Steps to create a database
Steps to create the table
Primary key column
Data types in SQL
How to add a field to the table?
데이터 베이스 MySQL 튜토리얼 Creating a MySQL database and table_MySQL

Creating a MySQL database and table_MySQL

Jun 01, 2016 pm 01:06 PM

How do you create a table to insert your form data into? In this tutorial I will explain how to do this with MySQL.

Creating a MySQL database and table

In the previous tutorials we have created a form to collect data and (if you did not already had this) set up a local development environment (with PHP, MySQL and Apache).

We now want to be able to insert form data into a database on the web server. That way we can retrieve those data any time we want later on.

A database is a collection of data. It’s organized in such a way that it can be quickly searched to retrieve specific data. MySQL is probably the most popular database management system. A MySQL database contains one or more tables. The data in a table are organized in records (= rows). Within each records there a several fields (= columns). We can use so-called queries to create databases, tables, retrieve data, etc. The SQL in MySQL stands for Structured Query Language. In this tutorial you will learn the basics of this language.

This tutorial supposes that you have already setup a development environment with PHP and MySQL on your local machine or know how to do so. If not I advice you to first read thetutorial how to set up a local development environment

Steps to create a database

To create a new database you need to:

  1. Log into phpMyAdmin (as the “root” user)
  2. Click on the tab “Databases” (at the top)
  3. Insert the name of the database into the field below “Create Database” (in the previous and next tutorials I’ll use the name ‘all_sports’ for the database).
  4. From the dropdown menu “Collation” choose the option “utf8_general_ci”.
  5. Then click on the button “Create”.

You should now see the name of the new database appear both in the table below Create Database and in the panel to the left.

Steps to create the table

To create a table inside a database you:

  1. First need to select that database by clicking on its name in the panel on the left
  2. Then click on the “SQL” tab (at the top)
  3. Insert the code shown below into the query box (and then click on Go)

SQL - query to create table

CREATETABLEmembers(

idINTUNSIGNEDNOTNULLAUTO_INCREMENTKEY,

firstnameVARCHAR(255)NOTNULL,

lastnameVARCHAR(255)NOTNULL,

genderVARCHAR(6)NOTNULL,

dobDATENOTNULL,

addressVARCHAR(255)NOTNULL,

cityVARCHAR(128)NOTNULL,

zipcodeVARCHAR(128)NOTNULL,

phoneVARCHAR(128)  NOTNULL,

emailVARCHAR(255)NOTNULL)

If everything went as it should you should see the name of the table (“members” in my code above) listed below the name of the database in the panel on the left.

You can see/check the structure of the table you just created by clicking on the tab “Structure”; then click on the name of the table (e.g. “members”); then click again on the tab “Structure” (which is now displayed to the right of the tab “Browse”).

Primary key column

The first column/field has nothing to do with the form we created earlier but contains the variable “id”. With this field we can make sure that every record in the table is unique.

The column named “id” has the following characteristics:

INT UNSIGNEDThe INT data type makes the column take an integer. Unsigned means that no negative values are allowed.

NOT NULLWith NOT NULL we ensure that every column has a value.

AUTO_INCREMENTCauses MySQL to set a unique value for this column in every row. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. This way we are guaranteed that each record has a unique value.

KEYAn auto-increment column is useful as a key, because you will tend to search for rows based on this column. When you look at the structure information you will notice that the key symbol for this field has a different color.

Each entry in the column “id” will now have a unique number, with the first starting at 1 and the others counting upward from there. And whenever a new row is inserted, its “id” column will automatically be given the next number in sequence.

Data types in SQL

We have defined the fields in the table with the use of various SQL data types:

VARCHAR (n)The VARCHAR data type accepts text strings (the term VARCHAR stands for VARiable length CHARacter string). With VARCHAR data type there is a limit on the size of the field in the table. This limit is set with (n). As you can see I have sometimes set this limit to 255 or 128.

For this table I did not use the data type CHAR. But it’s good to be aware of this data type and how it differs from the VARCHAR type. Both CHAR and VARCHAR accept text strings and impose a limit on the size of the field. The difference between these 2 data types is that with CHAR every string has the specified size. If I had used CHAR(6) for Gender than the string “male” would be padded with (two) spaces. A VARCHAR field does not pad the text; it lets the size of the field vary to fit the text that is inserted. But VARCHAR requires a small amount of overhead to keep track of the size of each value. So CHAR is slightly more efficient if the sizes are similar in all records, whereas VARCHAR is more efficient if sizes can vary a lot and get large. In addition, the overhead causes access to VARCHAR data to be slightly slower than to CHAR data.

Besides VARCHAR and CHAR we could also use the TEXT data type when creating a table. With First Name etc. you might be tempted to use the data type TEXT. However with the TEXT data type you will never search more than a certain number of leading characters in a field. Because a user will also want to be able to search for part of a name I used the VARCHAR type.

DATEWith the data type DATE the input will be formatted like this “yyyy-mm-dd”. You’ll notice that this is slightly different from the format in the form (mm/dd/yyyy). When you insert data with the form into the database and check the result you will see that this doesn’t pose a problem and the form date will be translated correctly into the SQL format.

INTINT stands for Integer. When your data consist of numbers (e.g. phone number) you might be tempted to use the INT data type. My advice is to only use the INT data type for the primary key and for data that you want to do mathematics on (e.g. add, multiply). A phone number for instance is not something that you’re going to multiply with another number. The same goes for a ZIP code. That’s why we defined them as VARCHAR data types.

How to add a field to the table?

You might have noticed that we “forgot” one field (“region”) when we created the table. This allows me to explain how we can add a field/column to an existing table.

Go to the tab that shows the structure of the table. Below the structure you will see the option to add one (or more) column(s) to the table.

  1. Choose the option “After”
  2. From the dropdown menu choose “zipcode”
  3. Click on Go

You then get a window asking you to define the field/column:

  1. For Name insert “region” (without the quotation marks)
  2. For Type choose VARCHAR
  3. For Length/values insert 128
  4. For Collation choose “utf8_general_ci” (without the quotation marks)
  5. Then click on Save

Now that our database/table is ready we can start writing the PHP script that will send the data from the form to the MySQL database.

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Docker에서 MySQL 메모리 사용을 줄입니다 Docker에서 MySQL 메모리 사용을 줄입니다 Mar 04, 2025 pm 03:52 PM

Docker에서 MySQL 메모리 사용을 줄입니다

Alter Table 문을 사용하여 MySQL에서 테이블을 어떻게 변경합니까? Alter Table 문을 사용하여 MySQL에서 테이블을 어떻게 변경합니까? Mar 19, 2025 pm 03:51 PM

Alter Table 문을 사용하여 MySQL에서 테이블을 어떻게 변경합니까?

MySQL의 문제를 해결하는 방법 공유 라이브러리를 열 수 없습니다. MySQL의 문제를 해결하는 방법 공유 라이브러리를 열 수 없습니다. Mar 04, 2025 pm 04:01 PM

MySQL의 문제를 해결하는 방법 공유 라이브러리를 열 수 없습니다.

sqlite 란 무엇입니까? 포괄적 인 개요 sqlite 란 무엇입니까? 포괄적 인 개요 Mar 04, 2025 pm 03:55 PM

sqlite 란 무엇입니까? 포괄적 인 개요

Linux에서 MySQL을 실행합니다 (Phpmyadmin이있는 Podman 컨테이너가 포함되지 않음) Linux에서 MySQL을 실행합니다 (Phpmyadmin이있는 Podman 컨테이너가 포함되지 않음) Mar 04, 2025 pm 03:54 PM

Linux에서 MySQL을 실행합니다 (Phpmyadmin이있는 Podman 컨테이너가 포함되지 않음)

MacOS에서 여러 MySQL 버전을 실행 : 단계별 가이드 MacOS에서 여러 MySQL 버전을 실행 : 단계별 가이드 Mar 04, 2025 pm 03:49 PM

MacOS에서 여러 MySQL 버전을 실행 : 단계별 가이드

인기있는 MySQL GUI 도구는 무엇입니까 (예 : MySQL Workbench, Phpmyadmin)? 인기있는 MySQL GUI 도구는 무엇입니까 (예 : MySQL Workbench, Phpmyadmin)? Mar 21, 2025 pm 06:28 PM

인기있는 MySQL GUI 도구는 무엇입니까 (예 : MySQL Workbench, Phpmyadmin)?

일반적인 취약점 (SQL 주입, 무차별 적 공격)에 대해 MySQL을 어떻게 보호합니까? 일반적인 취약점 (SQL 주입, 무차별 적 공격)에 대해 MySQL을 어떻게 보호합니까? Mar 18, 2025 pm 12:00 PM

일반적인 취약점 (SQL 주입, 무차별 적 공격)에 대해 MySQL을 어떻게 보호합니까?

See all articles