Php 将stmt结果存储在数组中,位于数组内部

Php 将stmt结果存储在数组中,位于数组内部,php,mysqli,Php,Mysqli,因此,我尝试创建多个结果数组,并在主数组中用我的语句的结果填充它们 但是,每次循环通过时,结果数组似乎都被覆盖,而不是创建额外的数组 我的代码: function retrieve_clients() { $coach_id = $_SESSION['user_details']['id']; $connection = connection(); $statement = select($connection, '*', 'relations', 'coach_id'

因此,我尝试创建多个结果数组,并在主数组中用我的语句的结果填充它们

但是,每次循环通过时,结果数组似乎都被覆盖,而不是创建额外的数组

我的代码:

function retrieve_clients() {
    $coach_id = $_SESSION['user_details']['id'];

    $connection = connection();
    $statement = select($connection, '*', 'relations', 'coach_id', '=');
    $statement->bind_param('i', $coach_id);

    if ($statement->execute()) {
        $statement->bind_result($id, $coach_id, $client_id, $relation_date);

        while ($statement->fetch()) {
            $_SESSION['clients'] = array(
                array($id, $coach_id, $client_id, $relation_date)
            );
       }
    }
$statement->close();
}

我再也弄不明白了。请原谅我,因为我还是编程新手。

您需要通过在变量末尾添加[]来为您的客户机添加另一个维度

$_SESSION['clients'][] = array(
            array($id, $coach_id, $client_id, $relation_date)
        );

这是因为在下面的行中替换了客户的价值

$_SESSION['clients'] = array(
                array($id, $coach_id, $client_id, $relation_date)
            );
您需要做的是在循环之前首先创建一个客户机数组,然后将每个数组追加到主数组中

像这样,

$_SESSION['clients']=array();
while ($statement->fetch()) {
            $_SESSION['clients'][] = array(
                array($id, $coach_id, $client_id, $relation_date)
            );

帮你自己一个忙,停止使用mysqli以及自制的select函数

使用PDO,您将拥有一个健全的代码:

function retrieve_clients() {
    $sql = "SELECT * FROM relation WHERE coach_id = ?";
    $statement = connection()->prepare($sql); // here goes your SQL
    $statement->execute([$_SESSION['user_details']['id']]); // here goes a parameter
    $_SESSION['clients'] = $statement->fetchAll(); // and here you have your array
}

我认为其他答案是正确的,但是它们增加了一个不必要的、可能不受欢迎的维度。尝试使用[]添加动态维度,但删除覆盖以下内容的数组维度之一:

$_SESSION['clients'][] = array($id, $coach_id, $client_id, $relation_date);

在select$\u会话本身作为数组时使用的数据库库是什么。无需声明。+1用于初始化$\u会话['clients']。我认为这是个好主意,即使这不是绝对必要的。这样,如果查询没有返回任何内容,$\u会话['clients']将是一个空数组,而不是一个未定义的索引。是的,这就是为什么我将它初始化为数组。哎呀,我错过了。抢手货使用PDO,准备好的语句要容易得多。