PHP

php如何创建用户表并添加数据

小亿
131
2024-03-18 19:11:38
栏目: 编程语言

要创建用户表并添加数据,可以按照以下步骤进行:

  1. 创建数据库连接:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
  1. 创建用户表:
$sql = "CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(30) NOT NULL,
    email VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL
)";
if ($conn->query($sql) === TRUE) {
    echo "Table users created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}
  1. 添加用户数据:
$username = "JohnDoe";
$email = "johndoe@example.com";
$password = "password123";

$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
  1. 关闭数据库连接:
$conn->close();

以上是一个简单的示例,你可以根据自己的需求对表结构和数据进行更改。在实际应用中,建议使用预处理语句来防止SQL注入攻击。

0
看了该问题的人还看了