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

avatar
作者
筋斗云
阅读量:0

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

  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注入攻击。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!