Home Backend Development PHP Tutorial How to create a MySQL table through PHP

How to create a MySQL table through PHP

May 07, 2018 pm 01:53 PM
mysql php data sheet

How to create a mysql table through php. This article will explain in detail how to create a mysql table through php.

Creating a MySQL table using MySQLi and PDO

The CREATE TABLE statement is used to create a MySQL table.

Before creating the table, we need to use use myDB to select the database to operate:

use myDB;

We will create a table named "MyGuests" Table, with 5 columns: "id", "firstname", "lastname", "email" and "reg_date":

CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)

Notes in the above table:

Data typeSpecifies what type of data the column can store. For complete data types please refer to our Data Types Reference Manual.

After setting the data type, you can specify the properties of other options for each column:

NOT NULL - Each row must contain a value (cannot be empty), the null value is not Allowed.

DEFAULT value - Set the default value

UNSIGNED - Use unsigned numeric type, 0 and positive numbers

AUTO INCREMENT - Set the value of the MySQL field every time when adding a record Automatically increase 1 times

PRIMARY KEY - Set the unique identification of each record in the data table. Typically the column's PRIMARY KEY is set to the ID value, used with AUTO_INCREMENT.

Each table should have a primary key (this column is the "id" column), and the primary key must contain a unique value.

The following example shows how to create a table in PHP:

Example (MySQLi - Object-oriented)

<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB";// 创建连接$conn = new mysqli($servername, $username, $password, $dbname);// 检测连接if ($conn->connect_error) {    die("连接失败: " . $conn->connect_error);} // 使用 sql 创建数据表$sql = "CREATE TABLE MyGuests (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL,lastname VARCHAR(30) NOT NULL,email VARCHAR(50),reg_date TIMESTAMP)";if ($conn->query($sql) === TRUE) {    echo "Table MyGuests created successfully";} else {    echo "创建数据表错误: " . $conn->error;}$conn->close();?>
实例 (MySQLi - 面向过程)
<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB";// 创建连接$conn = mysqli_connect($servername, $username, $password, $dbname);// 检测连接if (!$conn) {    die("连接失败: " . mysqli_connect_error());}// 使用 sql 创建数据表$sql = "CREATE TABLE MyGuests (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL,lastname VARCHAR(30) NOT NULL,email VARCHAR(50),reg_date TIMESTAMP)";if (mysqli_query($conn, $sql)) {    echo "数据表 MyGuests 创建成功";} else {    echo "创建数据表错误: " . mysqli_error($conn);}mysqli_close($conn);?>
实例 (PDO)
<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDBPDO";try {    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);    // 设置 PDO 错误模式,用于抛出异常    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    // 使用 sql 创建数据表    $sql = "CREATE TABLE MyGuests (    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,     firstname VARCHAR(30) NOT NULL,    lastname VARCHAR(30) NOT NULL,    email VARCHAR(50),    reg_date TIMESTAMP    )";    // 使用 exec() ,没有结果返回     $conn->exec($sql);    echo "数据表 MyGuests 创建成功";}catch(PDOException $e){    echo $sql . "<br>" . $e->getMessage();}$conn = null;?>

This article explains PHP in detail For the operation of creating a data table, please pay attention to the php Chinese website for more learning materials.

Related recommendations:

How to create a database through PHP MySQL

PHP connection to MySQL related knowledge and operations

Introduction to PHP MySQL (database related knowledge)

The above is the detailed content of How to create a MySQL table through PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
How to work with arrays in php How to work with arrays in php Aug 20, 2025 pm 07:01 PM

PHParrayshandledatacollectionsefficientlyusingindexedorassociativestructures;theyarecreatedwitharray()or[],accessedviakeys,modifiedbyassignment,iteratedwithforeach,andmanipulatedusingfunctionslikecount(),in_array(),array_key_exists(),array_push(),arr

How to use the $_COOKIE variable in php How to use the $_COOKIE variable in php Aug 20, 2025 pm 07:00 PM

$_COOKIEisaPHPsuperglobalforaccessingcookiessentbythebrowser;cookiesaresetusingsetcookie()beforeoutput,readvia$_COOKIE['name'],updatedbyresendingwithnewvalues,anddeletedbysettinganexpiredtimestamp,withsecuritybestpracticesincludinghttponly,secureflag

You are not currently using a display attached to an NVIDIA GPU [Fixed] You are not currently using a display attached to an NVIDIA GPU [Fixed] Aug 19, 2025 am 12:12 AM

Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

How to work with dates and times in php How to work with dates and times in php Aug 20, 2025 pm 06:57 PM

UseDateTimefordatesinPHP:createwithnewDateTime(),formatwithformat(),modifyviaadd()ormodify(),settimezoneswithDateTimeZone,andcompareusingoperatorsordiff()togetintervals.

How to change the GROUP_CONCAT separator in MySQL How to change the GROUP_CONCAT separator in MySQL Aug 22, 2025 am 10:58 AM

You can customize the separator by using the SEPARATOR keyword in the GROUP_CONCAT() function; 1. Use SEPARATOR to specify a custom separator, such as SEPARATOR'; 'The separator can be changed to a semicolon and plus space; 2. Common examples include using the pipe character '|', space'', line break character '\n' or custom string '->' as the separator; 3. Note that the separator must be a string literal or expression, and the result length is limited by the group_concat_max_len variable, which can be adjusted by SETSESSIONgroup_concat_max_len=10000; 4. SEPARATOR is optional

How to select data from a table in MySQL? How to select data from a table in MySQL? Aug 19, 2025 pm 01:47 PM

To select data from MySQL table, you should use SELECT statement, 1. Use SELECTcolumn1, column2FROMtable_name to obtain the specified column, or use SELECT* to obtain all columns; 2. Use WHERE clause to filter rows, such as SELECTname, ageFROMusersWHEREage>25; 3. Use ORDERBY to sort the results, such as ORDERBYageDESC, representing descending order of age; 4. Use LIMIT to limit the number of rows, such as LIMIT5 to return the first 5 rows, or use LIMIT10OFFSET20 to implement paging; 5. Use AND, OR and parentheses to combine

How to use the LIKE operator in MySQL How to use the LIKE operator in MySQL Aug 22, 2025 am 12:23 AM

TheLIKEoperatorinMySQLisusedtosearchforpatternsintextdatausingwildcards;1.Use%tomatchanysequenceofcharactersandtomatchasinglecharacter;2.Forexample,'John%'findsnamesstartingwithJohn,'%son'findsnamesendingwithson,'%ar%'findsnamescontainingar,'\_\_\_\_

PS oil paint filter greyed out fix PS oil paint filter greyed out fix Aug 18, 2025 am 01:25 AM

TheOilPaintfilterinPhotoshopisgreyedoutusuallybecauseofincompatibledocumentmodeorlayertype;ensureyou'reusingPhotoshopCS6orlaterinthefulldesktopversion,confirmtheimageisin8-bitperchannelandRGBcolormodebycheckingImage>Mode,andmakesureapixel-basedlay

See all articles