PHP

php中怎么使用pdo查询数据

小亿
144
2024-02-01 10:35:40
栏目: 编程语言

在使用PDO查询数据时,可以按照以下步骤进行操作:

  1. 连接到数据库:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
  1. 编写SQL查询语句:
$sql = "SELECT * FROM table_name";
  1. 准备并执行查询语句:
$stmt = $conn->prepare($sql);
$stmt->execute();
  1. 获取查询结果:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1. 处理查询结果:
foreach($result as $row) {
    echo $row['column_name'];
}

完整的示例代码如下:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_name";

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

    $sql = "SELECT * FROM table_name";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach($result as $row) {
        echo $row['column_name'];
    }
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

注意替换$servername$username$password$dbname为实际的数据库连接信息。同时,将table_namecolumn_name替换为实际的表名和列名。

0
看了该问题的人还看了