PHP操作MySQL数据库实验
时间: 2023-11-16 19:11:42 浏览: 84
数据库实验1 MYSQL数据库SQL语句练习实验.doc
好的,下面是一个简单的PHP操作MySQL数据库的实验:
1. 首先,需要创建一个MySQL数据库和表。可以使用以下SQL语句:
```
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL
);
```
2. 接下来,创建一个PHP文件,连接到MySQL数据库并插入一些数据。可以使用以下代码:
```
<?php
//连接到MySQL数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
$conn = mysqli_connect($servername, $username, $password, $dbname);
//检查连接是否成功
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//插入数据
$sql = "INSERT INTO users (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
//关闭连接
mysqli_close($conn);
?>
```
3. 运行PHP文件,可以看到输出 "New record created successfully",表示数据已成功插入。可以使用以下SQL语句查询数据:
```
SELECT * FROM users;
```
4. 最后,可以使用以下PHP代码从MySQL数据库中检索数据:
```
<?php
//连接到MySQL数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
$conn = mysqli_connect($servername, $username, $password, $dbname);
//检查连接是否成功
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//检索数据
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// 输出数据
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
//关闭连接
mysqli_close($conn);
?>
```
以上就是一个简单的PHP操作MySQL数据库的实验。
阅读全文