PHP 数据库

php如何查询数据库并显示内容

小亿
179
2024-05-23 17:37:10
栏目: 编程语言

要查询数据库并显示内容,可以使用PHP中的MySQLi扩展或PDO扩展。以下是一个简单的示例:

使用MySQLi扩展:

<?php
$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 结果";
}

$conn->close();
?>

使用PDO扩展:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare("SELECT id, name, email FROM users");
    $stmt->execute();

    // 设置结果集为关联数组
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    foreach($stmt->fetchAll() as $row) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
    }

} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
?>

无论使用MySQLi扩展还是PDO扩展,都需要替换示例中的主机名、用户名、密码和数据库名以及查询的数据表和字段名称。

0
看了该问题的人还看了