溫馨提示×

php如何創(chuàng)建用戶表并添加數(shù)據(jù)

PHP
小億
131
2024-03-18 19:11:38
欄目: 編程語言

要創(chuàng)建用戶表并添加數(shù)據(jù),可以按照以下步驟進行:

  1. 創(chuàng)建數(shù)據(jù)庫連接:
$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. 創(chuàng)建用戶表:
$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. 添加用戶數(shù)據(jù):
$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. 關(guān)閉數(shù)據(jù)庫連接:
$conn->close();

以上是一個簡單的示例,你可以根據(jù)自己的需求對表結(jié)構(gòu)和數(shù)據(jù)進行更改。在實際應(yīng)用中,建議使用預(yù)處理語句來防止SQL注入攻擊。

0