Home > Article > Backend Development > How to create a simple student table with PHP+MySQL
How to create a student table? This is a problem that every beginner programming in PHP faces. In this article, we will show you how to create a simple students table using PHP and MySQL and add information to it.
Step 1: Create a database
First, you need to create a database to store the student table. Databases can be created using the MySQL command line or any MySQL client. The following is an example of using the MySQL command line to create a database:
mysql> CREATE DATABASE students;
Step 2: Create a table
Before creating the student table, we need to first define the columns in the table and the data in each column type. In this example, we will use the following column names and data types:
Column Name | Data Type |
---|---|
id | INT |
name | VARCHAR(50) |
VARCHAR(50) | |
phone | VARCHAR(20) |
Required To create the students table, please use the following SQL statement:
CREATE TABLE students ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL, phone VARCHAR(20) NOT NULL );
The above code will create a table named "students", which contains four columns: id, name, email and phone. Among them, the id column is the primary key, self-increasing, which will be used to uniquely identify each student.
Step 3: Write PHP code
Now that we have created the student table, we need to write PHP code to add information to it. The following is an example of inserting data into the student table using PHP and MySQL:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "students"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 准备 SQL 语句 $sql = "INSERT INTO students (name, email, phone) VALUES ('John Doe', 'johndoe@example.com', '123-456-7890')"; if ($conn->query($sql) === TRUE) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
The above code will insert a new record into the student table with the name John Doe, email address johndoe@example.com, and phone number is 123-456-7890.
You can use a similar method to insert more student data into the student table. For example, you could use an HTML form to accept user-entered data and insert it into the Students table using PHP.
Conclusion
In this article, we showed you how to create a simple student table using PHP and MySQL and insert data into it. Although this is just an entry-level example, it can help you better understand how to build more complex applications using PHP and MySQL.
The above is the detailed content of How to create a simple student table with PHP+MySQL. For more information, please follow other related articles on the PHP Chinese website!