PHP PDO(PHP Data Objects)是另一种用于与数据库进行交互的数据库抽象层。与MySQLi相比,PDO更通用,支持多种数据库系统。以下是一个使用PDO连接到MySQL数据库、执行查询和插入数据的简单示例:

1. 连接到数据库:
<?php
$servername = "localhost";  // 数据库服务器地址
$username = "your_username";  // 数据库用户名
$password = "your_password";  // 数据库密码
$dbname = "your_database";  // 数据库名

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // 设置 PDO 错误模式为异常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "连接成功";
} catch(PDOException $e) {
    echo "连接失败: " . $e->getMessage();
}
?>

2. 执行查询:
<?php
try {
    $stmt = $conn->prepare("SELECT id, name, email FROM your_table"); 
    $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 "查询失败: " . $e->getMessage();
}
?>

3. 插入数据:
<?php
try {
    $name = "John Doe";
    $email = "john@example.com";

    $stmt = $conn->prepare("INSERT INTO your_table (name, email) VALUES (:name, :email)");
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':email', $email);

    $stmt->execute();

    echo "新记录插入成功";
} catch(PDOException $e) {
    echo "插入失败: " . $e->getMessage();
}
?>

确保替换代码中的 "your_username"、"your_password"、"your_database" 和 "your_table" 等信息为实际数据库信息。使用PDO的好处之一是可以轻松地切换到其他数据库系统,只需修改连接字符串即可。


转载请注明出处:http://www.zyzy.cn/article/detail/13864/PHP