Home >Backend Development >PHP Tutorial >How to create a MySQL table using PHP?
Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.
Creating a MySQL table using PHP is a simple process, which involves the following steps:
<?php // 连接到 MySQL 数据库 $servername = "localhost"; $username = "root"; $password = "mypassword"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password); // 检查连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 创建数据库(如果不存在) $sql = "CREATE DATABASE IF NOT EXISTS $dbname"; if ($conn->query($sql) === TRUE) { echo "数据库创建成功"; } else { echo "数据库创建失败: " . $conn->error; } // 选择数据库 $conn->select_db($dbname); // 创建表 $sql = "CREATE TABLE IF NOT EXISTS users ( id INT NOT NULL AUTO_INCREMENT, username VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, PRIMARY KEY (id) )"; // 执行查询 if ($conn->query($sql) === TRUE) { echo "表创建成功"; } else { echo "表创建失败: " . $conn->error; } // 关闭连接 $conn->close(); ?>
Suppose you want to create a A table named "users" with columns "id", "username", and "email". You can use the following code:
// 连接到 MySQL 数据库 $conn = new mysqli($servername, $username, $password, $dbname); // 创建表 $sql = "CREATE TABLE IF NOT EXISTS users ( id INT NOT NULL AUTO_INCREMENT, username VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, PRIMARY KEY (id) )"; // 执行查询 if ($conn->query($sql) === TRUE) { echo "表创建成功"; } else { echo "表创建失败: " . $conn->error; } // 关闭连接 $conn->close();
The above is the detailed content of How to create a MySQL table using PHP?. For more information, please follow other related articles on the PHP Chinese website!