编写一个PHP程序,该程序要实现以下功能:连接本地的MySQL数据库,在MySQL中创建一个名为phptest的数据库,在phptest数据库中创建一张student 表,在student表中插入两名学生的id、name、age、gender记录。
时间: 2024-12-04 10:26:48 浏览: 25
在PHP中,你可以使用mysqli或PDO扩展来连接MySQL数据库并执行SQL操作。以下是一个简单的示例程序,展示如何完成上述任务:
```php
<?php
// 数据库配置信息
$servername = "localhost";
$username = "your_username";
$password = "your_password";
// 创建连接
$conn = new mysqli($servername, $username, $password);
// 检查连接是否成功
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 创建数据库
$sql = "CREATE DATABASE IF NOT EXISTS phptest";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// 选择刚创建的数据库
$conn->select_db('phptest');
// 创建学生表
$sql = "CREATE TABLE IF NOT EXISTS student (
id INT AUTO_INCREMENT,
name VARCHAR(50),
age INT,
gender ENUM('Male', 'Female'),
PRIMARY KEY (id)
)";
if ($conn->query($sql) === TRUE) {
echo "Table student created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// 插入数据
$sql = "INSERT INTO student (name, age, gender) VALUES ('Student1', 20, 'Male'), ('Student2', 22, 'Female')";
if ($conn->query($sql) === TRUE) {
echo "Records inserted successfully";
} else {
echo "Error inserting records: " . $conn->error;
}
// 关闭连接
$conn->close();
?>
```
阅读全文