Home >Backend Development >PHP Tutorial >How to create a MySQL table using PHP?

How to create a MySQL table using PHP?

王林
王林Original
2024-06-04 13:57:131221browse

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.

如何使用 PHP 创建 MySQL 表?

How to create a MySQL table using PHP?

Creating a MySQL table using PHP is a simple process, which involves the following steps:

Prerequisites:

  • PHP is installed and configured
  • MySQL database server
  • MySQL database user and password

Code:

<?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();
?>

Practical case:

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!

Statement:
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