php - 回显来自 mySQL 的多个响应

标签 php mysql mysqli

我想回显来自 mySQL 数据库的各种响应而不重复它们。

表格如下所示:

+----+----------+---------------------+----------+
| id | user     | timestamp           | champion |
+----+----------+---------------------+----------+
| 1  | Watrasei | 2015-11-13 22:31:27 | yasuo    |
+----+----------+---------------------+----------+
| 2  | Meta Nex | 2016-04-29 02:47:33 | yasuo    |
+----+----------+---------------------+----------+
| 3  | Meta Nex | 2016-04-30 02:27:53 | yasuo    |
+----+----------+---------------------+----------+

当我直接将此代码输入 phpMyAdmin 时,响应是预期的:

SELECT DISTINCT user FROM champions3 WHERE champion = 'yasuo'

sql response

但是,当我使用此 PHP 代码发出请求并回显结果时,仅显示最后的结果:

<?php
$dbconnect = new MySQLi("localhost","root","pass","database");
if ($dbconnect ->connect_errno){
    die("Connection failed: " . $dbconnect ->connect_error);
}

$creatorSQL = "
    SELECT DISTINCT user 
    FROM champions3 
    WHERE champion = 'yasuo'
";
$creatorQuery = $dbconnect->query($creatorSQL);

// Convert all results into variables. If there is more than one result, put a comma in front of the name.
$i = 1;
while ($creator = mysqli_fetch_assoc($creatorQuery)) {
    if($i = 1) {
        ${'author'.$i} = '<a>'.$creator["user"].'</a>';
    }
    else {
        ${'author'.$i} = ', <a>'.$creator["user"].'</a>';
    }
    $i++;
}

echo $author1, $author2, $author3, $author4, $author5, $author6, $author7;

mysqli_close($dbconnect);
?>

Real result

预期结果应该是:Meta Nex,Watrasei

提前谢谢您。

最佳答案

<?php
$dbconnect = new MySQLi("localhost","root","pass","database");
if ($dbconnect ->connect_errno){
    die("Connection failed: " . $dbconnect ->connect_error);
}

$creatorSQL = "
    SELECT DISTINCT user 
    FROM champions3 
    WHERE champion = 'yasuo'
";
$creatorQuery = $dbconnect->query($creatorSQL);

// Convert all results into variables. If there is more than one result, put a comma in front of the name.
$i = 1;
while ($creator = mysqli_fetch_assoc($creatorQuery)) {
    if($i == 1) {
        ${'author'.$i} = '<a>'.$creator["user"].'</a>';
    }
    else {
        ${'author'.$i} = ', <a>'.$creator["user"].'</a>';
    }
    $i++;
}

echo $author1, $author2, $author3, $author4, $author5, $author6, $author7;

mysqli_close($dblogin);
?>

关于php - 回显来自 mySQL 的多个响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951255/

相关文章:

php - 在 php 上加入具有相同列的两列

mysql - 按 ID 移位更新表

javascript - 如何使用 While 循环使用 DataTables 显示 MYSQL 数据

javascript - 通过 PHP 流式传输时,Safari 中的音频持续时间总是返回无穷大

php - MySQL 将包含 200 万条记录的查询写入新表

php - android如何获取json数组到listview

mysql - 无法使用 Django 3.0.3 中的迁移 API 使用 ModelState 和 ProjectState 进行迁移

php - 如何同时运行两个数组

php - 如何从数据库中获取逗号分隔值

php - PHP 和 Mysqli 中的登录错误脚本