PHP可以与数据库配合使用以实现数据的存储、查询、更新和删除操作。以下是使用PHP和MySQL数据库进行配合的简单示例:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 结果";
}
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "UPDATE users SET name='Jane Doe' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "记录更新成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "DELETE FROM users WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "记录删除成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
通过以上代码示例,可以看到PHP通过MySQLi扩展提供的功能,实现了与MySQL数据库的连接、查询、插入、更新和删除操作。这样就可以使用PHP编写动态的网页应用程序,并与数据库进行数据交互。