Php pdo Select 声明returns 一个数组和那个数组用于再次查询数据库

Php pdo Select statement that returns an array and that array is used to query the database again

我一直在想办法解决这个问题,但我不确定该怎么做。我有一个 select 查询数据库的语句和 returns 一个数组。然后使用该数组再次查询数据库。我不确定如何保存第二个数组。

        $stmt = $dbh->query("SELECT user_id FROM users WHERE username = '" . $user_name . "'");
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $user_id = $row['user_id'];

        $stmt = $dbh->query("SELECT friend_id FROM friends WHERE user_id ='" . $user_id . "'");
        $ret_array = $stmt->fetchAll(PDO::FETCH_ASSOC);

        for($i = 0; $i<count($ret_array); $i++) {
            $stmt = $dbh->query("SELECT profile_path, username FROM users WHERE user_id=" .$ret_array[$i]['friend_id']);
        }
        $show_all_friends = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $show_all_friends;

这是我的代码,我希望将在 forloop 中获得的值保存到 $show_all_friends 中。我该怎么做?

请使用以下代码更改您的代码

$stmt = $dbh->query("SELECT user_id FROM users WHERE username = '" . $user_name . "'");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $user_id = $row['user_id'];

    $stmt = $dbh->query("SELECT friend_id FROM friends WHERE user_id ='" . $user_id . "'");
    $ret_array = $stmt->fetchAll(PDO::FETCH_ASSOC);

    for($i = 0; $i<count($ret_array); $i++) {
        $stmt = $dbh->query("SELECT profile_path, username FROM users WHERE user_id=" .$ret_array[$i]['friend_id']);
        $show_all_friends[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }


    return $show_all_friends;

希望对您有所帮助

您不必进行循环,只需使用绑定方法进行 2 次查询即可获得更高的安全性和性能。

$sth = $dbh->prepare("SELECT user_id FROM users WHERE username = ?");
$sth->bindParam(1, $user_name, PDO::PARAM_STR);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$user_id = $row['user_id'];

$sth = $dbh->prepare('SELECT u.profile_path, u.username 
FROM users u JOIN friends f on f.friend_id = u.user_id
WHERE f.user_id = ?');
$sth->bindParam(1, $user_id, PDO::PARAM_INT);
$sth->execute();

return $sth->fetchAll(PDO::FETCH_ASSOC);

通过两个 JOINS 使用单个查询。
您可以 "use" 相同的 table 两次,方法是在查询中给它唯一的别名,这样任何对 table 的引用都是明确的。
正如你的问题的评论中提到的,这不适用于 MySQL 的临时 tables。因此,以下示例 不会 在 setup() 函数中使用 CREATE TEMPORARY TABLE....。我通常会尽量避免这种情况。因此,请记住,此示例可能会覆盖现有的 tables(尽管我希望 table 名称非常独特)并且它会将数据保存在您的数据库服务器上。

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');  
//echo 'client version: ', $pdo->getAttribute(PDO::ATTR_CLIENT_VERSION), "\n";
//echo 'server version: ', $pdo->getAttribute(PDO::ATTR_SERVER_VERSION), "\n";
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($pdo);


$stmt = $pdo->prepare('
    SELECT
        u2.user_id
    FROM
        soNOTTEMPUsers as u1
    JOIN
        soNOTTEMPFriends as f
    ON
        u1.user_id=f.user_id
    JOIN
        soNOTTEMPUsers as u2
    ON
        f.friend_id=u2.user_id
    WHERE
        u1.username=:username
');

$stmt->bindParam('username', $username);
foreach( array('userA', 'userB', 'userC', 'userD') as $username ) {
    echo 'querying friends of ', $username, "\r\n";
    $stmt->execute();
    foreach( $stmt as $row ) {
        echo '  ', join(', ', $row), "\r\n";    
    }
}

function setup($pdo) {
    $queries = array(
        '
            CREATE TABLE IF NOT EXISTS soNOTTEMPUsers (
                user_id INT,
                username varchar(32),
                primary key(user_id)
            )
        ',
        '
            CREATE TABLE IF NOT EXISTS soNOTTEMPFriends (
                user_id INT,
                friend_id INT,
                primary key(user_id, friend_id)
            )
        ',
        "REPLACE soNOTTEMPUsers (user_id, username) VALUES
            (1, 'userA'), (2, 'userB'), (3, 'userC'), (4, 'userD')
        ",
        "REPLACE INTO soNOTTEMPFriends (user_id, friend_id) VALUES
            (1,2),(1,3),(1,4),
            (2,1),(2,3),(2,4),
            (3,1),(3,4),
            (4,1)
        ",
    );
    foreach( $queries as $q ) {
        $pdo->exec($q);
    }

}

打印

querying friends of userA
  2, 2
  3, 3
  4, 4
querying friends of userB
  1, 1
  3, 3
  4, 4
querying friends of userC
  1, 1
  4, 4
querying friends of userD
  1, 1

符合预期(虽然没有像 a friendof b <=> b friendof a 那样测试一致性)