Create Unique Index in PHP: Step-by-Step Guide

In PHP, creating a unique index for a data table can be achieved by using SQL statements. Here is a simple example:

<?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 = "CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(30) NOT NULL,
    email VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(50) NOT NULL
)";

if ($conn->query($sql) === TRUE) {
    echo "数据表创建成功";
} else {
    echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

In the example above, we added a unique index to the email field when creating the users data table. This ensures that the values in the email field are unique throughout the table, preventing duplicate values.

bannerAds