温馨提示×

php数据库搜索与子查询

PHP
小樊
81
2024-12-24 05:58:12
栏目: 编程语言

在PHP中,我们可以使用MySQLi或PDO扩展来执行数据库搜索和子查询。以下是使用这两种扩展的示例。

首先,确保已经创建了一个名为users的数据库表,其中包含以下字段:idusernameemail

使用MySQLi扩展:

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

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 子查询
$sql_sub = "SELECT username FROM users WHERE email = ?";
$stmt_sub = $conn->prepare($sql_sub);
$stmt_sub->bind_param("s", $email);
$email = "example@example.com";
$stmt_sub->execute();
$result_sub = $stmt_sub->get_result();
$user = $result_sub->fetch_assoc();
$username = $user["username"];

// 主查询
$sql_main = "SELECT * FROM users WHERE username = ?";
$stmt_main = $conn->prepare($sql_main);
$stmt_main->bind_param("s", $username);
$stmt_main->execute();
$result_main = $stmt_main->get_result();

if ($result_main->num_rows > 0) {
    while($row = $result_main->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["username"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 结果";
}

$stmt_sub->close();
$stmt_main->close();
$conn->close();
?>

使用PDO扩展:

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

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

    // 子查询
    $sql_sub = "SELECT username FROM users WHERE email = :email";
    $stmt_sub = $conn->prepare($sql_sub);
    $stmt_sub->bindParam(':email', $email);
    $email = "example@example.com";
    $stmt_sub->execute();
    $user = $stmt_sub->fetch(PDO::FETCH_ASSOC);
    $username = $user["username"];

    // 主查询
    $sql_main = "SELECT * FROM users WHERE username = :username";
    $stmt_main = $conn->prepare($sql_main);
    $stmt_main->bindParam(':username', $username);
    $stmt_main->execute();
    $result_main = $stmt_main->fetchAll(PDO::FETCH_ASSOC);

    foreach($result_main as $row) {
        echo "id: " . $row["id"]. " - Name: " . $row["username"]. " - Email: " . $row["email"]. "<br>";
    }
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}

$conn = null;
?>

这两个示例都首先执行子查询以获取特定用户的用户名,然后使用该用户名执行主查询以获取与该用户名相关的所有用户信息。

0