How to create a MySQL table through PHP
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 )
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

$_COOKIEisaPHPsuperglobalforaccessingcookiessentbythebrowser;cookiesaresetusingsetcookie()beforeoutput,readvia$_COOKIE['name'],updatedbyresendingwithnewvalues,anddeletedbysettinganexpiredtimestamp,withsecuritybestpracticesincludinghttponly,secureflag
![You are not currently using a display attached to an NVIDIA GPU [Fixed]](https://img.php.cn/upload/article/001/431/639/175553352135306.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

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

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

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

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

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