如何使用 php 从 mysql 表中选择数据建立数据库连接,使用 mysqli 或 pdo 扩展。准备查询语句。执行查询并获取结果。使用循环遍历结果数据并输出。
如何使用 PHP 从 MySQL 表中选择数据
前言
在 PHP 中,我们可以使用 MySQLi 或 PDO 扩展从 MySQL 数据库中选择数据。本文将演示如何使用这两种扩展来实现这一目标。
使用 MySQLi 扩展
1. 建立数据库连接
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }
2. 准备查询
$sql = "SELECT * 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 结果"; } $conn->close();
使用 PDO 扩展
1. 建立数据库连接
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "myDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { die("连接失败: " . $e->getMessage()); }
2. 准备查询
$sql = "SELECT * FROM users"; $stmt = $conn->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(); foreach($result as $row) { echo "id: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } $conn = null;
实战案例
假设我们有一个名为 "users" 的 MySQL 表,其中存储了用户数据。要从该表中选择所有数据,我们可以使用 приведенный 以上代码,如下所示:
// 使用 MySQLi 扩展 $servername = "localhost"; $username = "root"; $password = ""; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } $sql = "SELECT * 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 结果"; } $conn->close();
类似地,可以使用 PDO 扩展来选择数据,代码如下所示:
// 使用 PDO 扩展 $servername = "localhost"; $username = "root"; $password = ""; $dbname = "myDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { die("连接失败: " . $e->getMessage()); } $sql = "SELECT * FROM users"; $stmt = $conn->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(); foreach($result as $row) { echo "id: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } $conn = null;