如何使用 PHP 函数来操作数据库
使用 PHP 函数操作数据库
PHP 提供了强大的函数库,可以轻松高效地与数据库交互。本文将指导您了解如何使用 PHP 函数执行常见数据库操作,并附有实战案例。
连接数据库
<?php $servername = "localhost";$username = "root";$password = "password";$dbname = "mydb";// 创建连接$conn = new mysqli($servername, $username, $password, $dbname);// 检查连接if ($conn->connect_error) { die("连接失败:" . $conn->connect_error);}?>
查询数据库
立即学习“PHP免费学习笔记(深入)”;
<?php // 预备查询$stmt = $conn->prepare("SELECT * FROM customers WHERE name = ?");// 绑定参数$stmt->bind_param("s", $name);// 设置参数$name = "John Doe";// 执行查询$stmt->execute();// 绑定结果$stmt->bind_result($id, $name, $email);// 循环结果while ($stmt->fetch()) { echo "ID: $id, 姓名: $name, 邮箱: $email<br>";}// 关闭语句$stmt->close();?>
插入数据
<?php // 预备查询$stmt = $conn->prepare("INSERT INTO customers (name, email) VALUES (?, ?)");// 绑定参数$stmt->bind_param("ss", $name, $email);// 设置参数$name = "Jane Doe";$email = "jane.doe@example.com";// 执行查询$stmt->execute();// 获取自增 ID(如果有)$id = $conn->insert_id;// 关闭语句$stmt->close();echo "新记录已插入,ID 为:$id";?>
更新数据
<?php // 预备查询$stmt = $conn->prepare("UPDATE customers SET name = ? WHERE id = ?");// 绑定参数$stmt->bind_param("si", $name, $id);// 设置参数$name = "John Smith";$id = 1;// 执行查询$stmt->execute();// 关闭语句$stmt->close();echo "记录已更新";?>
删除数据
<?php // 预备查询$stmt = $conn->prepare("DELETE FROM customers WHERE id = ?");// 绑定参数$stmt->bind_param("i", $id);// 设置参数$id = 1;// 执行查询$stmt->execute();// 关闭语句$stmt->close();echo "记录已删除";?>
关闭连接
<?php // 关闭连接$conn->close();?>
实战案例:创建博客系统
<?php // 连接数据库...// 查询博客文章$stmt = $conn->prepare("SELECT * FROM blog_posts ORDER BY created_at DESC");$stmt->execute();$stmt->bind_result($id, $title, $content, $created_at);// 循环结果,显示博客文章while ($stmt->fetch()) { echo "<h1>$title</h1>"; echo "<p>$content</p>"; echo "<p>Created: $created_at</p>"; echo "<hr>";}// 关闭语句$stmt->close();?>