PHP 使用 PDO 获取 MySQL 结果

PHP PDO 允许你通过统一的界面使用多个数据库。它简化了常规数据库操作,例如结果获取。

本教程将解释如何获取从 PDO 语句返回的多个结果。你将在 while 循环中使用 PDOStatement.fetchAll、数组迭代和 fetch() 方法。

设置数据库

对于本教程,你需要一个 MySQL 数据库来学习。下载并安装 XAMPP 服务器。启动 XAMPP 控制面板并登录到 MySQL shell。

# This login command assumes that the
# password is empty and the user is "root"
mysql -u root -p

使用以下 SQL 查询创建一个名为 fruit_db 的数据库。

CREATEdatabasefruit_db;

输出:

Query OK, 1 row affected (0.001 sec)

要创建你可以使用的示例数据,请在 fruit_db 数据库上执行以下 SQL:

CREATETABLEfruit(idINTNOTNULLAUTO_INCREMENT,nameVARCHAR(20)NOTNULL,colorVARCHAR(20)NOTNULL,PRIMARYKEY(id))ENGINE=InnoDB;

输出:

Query OK, 0 rows affected (0.028 sec)

使用以下内容确认表存在:

DESCfruit;

输出:

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20) | NO   |     | NULL    |                |
| color | varchar(20) | NO   |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

建立表后,使用以下 SQL 插入示例数据:

INSERTINTOfruit(id,name,color)VALUES(NULL,'Banana','Yellow'),(NULL,'Pineapple','Green')

使用以下 SQL 确认数据存在:

SELECT*FROMfruit;

输出:

+----+-----------+--------+
| id | name      | color  |
+----+-----------+--------+
|  1 | Banana    | Yellow |
|  2 | Pineapple | Green  |
+----+-----------+--------+

现在,你可以从 PHP 中获取结果。

在 PHP 中使用 pdostatement.fetchall() 获取结果

在你可以使用 PDOStament.fetchAll() 获取结果之前,你需要连接到你之前创建的数据库。创建一个名为 config.php 的文件,并放置以下代码;如果你的数据库用户名和密码不同,请替换它们。

<?php
    # If necessary, replace the values for the
    # user and password variables
    $host = 'localhost';
	$database = 'fruit_db';
	$user = 'root';
	$password = '';
?>

当你想在文件中获取数据库结果时,你需要导入 config.php

创建另一个名为 fetchpdo.php 的文件。在文件中,你将执行以下操作:

  • 连接到数据库。
  • 创建一个新的 PDO 连接。
  • 使用 prepare() 方法创建一个准备好的 SQL 语句。
  • 执行语句。
  • 使用 fetchAll() 方法获取结果。

现在,在 fetchpdo.php 中键入以下代码。

<?php
    // Require the config file. It contains
	// the database connection
	require ('config.php');
	// Create a connection string
	$database_connection = "mysql:host=$host;dbname=$database;charset=UTF8";
	// Create a new PDO instance
	$pdo = new PDO($database_connection, $user, $password);
	// Prepare a SQL statement
	$statement = $pdo->prepare('SELECT name, color FROM fruit');
	// Execute the statement
	$statement->execute();
    // Fetch the results
    print("Fetch the result set:\n");
    $result = $statement->fetchAll(\PDO::FETCH_ASSOC);
    print "<pre>";
    print_r($result);
    print "</pre>";
?>

输出:

Array
(
    [0] => Array
        (
            [name] => Banana
            [color] => Yellow
        )
    [1] => Array
        (
            [name] => Pineapple
            [color] => Green
        )
)

通过迭代 PHP 中的 PDO 语句来获取结果

执行 SQL 准备语句后,你可以使用 while 循环迭代结果。你将在下一个代码块中找到详细信息。

<?php
    // Require the config file. It contains
    // the database connection
    require ('config.php');
    // Create a connection string
    $database_connection = "mysql:host=$host;dbname=$database;charset=UTF8";
    // Create a new PDO instance
    $pdo = new PDO($database_connection, $user, $password);
    // Prepare a SQL statement
    $statement = $pdo->prepare('SELECT name, color FROM fruit');
    // Execute the statement
    $statement->execute(array());
    // Iterate over the array
    foreach($statement as $row) {
        echo $row['name'] . "<br />";
    }
?>

输出:

Banana
Pineapple

在 PHP 中使用 PDO fetch() 方法获取结果

fetch() 方法将从结果中获取下一行。它允许你在 while 循环中使用它。

详细信息在下一个代码块中。

<?php
    // Require the config file. It contains
    // the database connection
    require ('config.php');
    // Create a connection string
    $database_connection = "mysql:host=$host;dbname=$database;charset=UTF8";
    // Create a new PDO instance
    $pdo = new PDO($database_connection, $user, $password);
    // Prepare a SQL statement
    $statement = $pdo->prepare('SELECT name, color FROM fruit');
    // Execute the statement
    $statement->execute(array());
    // Use while loop over the array
    while ($row = $statement->fetch()) {
        echo $row['name'] . "<br />";
    }
?>

PDO fetch() 方法的预处理结果

如果你希望对数据库数据进行预处理,可以使用 while 循环。然后将处理后的结果存储在一个数组中。以下代码向你展示了如何执行此操作。

<?php
    // Require the config file. It contains
    // the database connection
    require ('config.php');
    // Create a connection string
    $database_connection = "mysql:host=$host;dbname=$database;charset=UTF8";
    // Create a new PDO instance
    $pdo = new PDO($database_connection, $user, $password);
    // Create an empty array to store the results
    $result = [];
    // Prepare a SQL statement
    $statement = $pdo->prepare('SELECT name, color FROM fruit');
    // Execute the statement
    $statement->execute(array());
    // Iterate over the result and assign
    // new names to the table rows
    while ($row = $statement->fetch()) {
        $result[] = [
            'Fruit Name' => $row['name'],
            'Fruit Color' => $row['color'],
        ];
    }
    print "<pre>";
    print_r($result);
    print "</pre>";
?>

输出:

Array
(
    [0] => Array
        (
            [Fruit Name] => Banana
            [Fruit Color] => Yellow
        )
    [1] => Array
        (
            [Fruit Name] => Pineapple
            [Fruit Color] => Green
        )
)