如何从1列中检索所有用户名并在php中回显它

时间:2017-09-19 19:47:36

标签: php mysql arrays pdo

如何从示例

中的mysql DB中的一列返回所有用户名
username       age      height
  bob          20       5'1
  mary         29       4'0
  sue          25       5'8

如何回显用户名栏中的所有内容 out put example我想要bob, mary, sue

<?php

    include("db.php");


    $SQLSelect = $odb -> prepare("SELECT members, FROM username");
    $SQLSelect -> execute();
    while ($row =  $SQLSelect->fetch(PDO::FETCH_ASSOC))
    {
    $results = $row['members'];   
    }

    echo $results;


?>

1 个答案:

答案 0 :(得分:0)

方法1:通过循环获取的数据并应用implode()

来构建用户名字符串

请注意使用fetchAll()来获取所有表行。

<?php

include("db.php");

$sql = 'SELECT username FROM members';

$statement = $odb->prepare($sql);
$statement->execute();
$fetchedData = $statement->fetchAll(PDO::FETCH_ASSOC);

// Just for testing: Print fetched data list.
echo '<pre>' . print_r($fetchedData, TRUE) . '</pre>';

// Build the user names array.
// ... by looping through the fetched data.
$usernamesArray = [];
foreach ($fetchedData as $item) {
    $usernamesArray[] = $item['username'];
}

// ... OR directly, by using array_column().
// $usernamesArray = array_column($fetchedData, 'username');
//
// Just for testing: Print the user names array.
echo '<pre>' . print_r($usernamesArray, TRUE) . '</pre>';

// Build the user names string.
$usernamesString = implode(',', $usernamesArray);

// Print the user names string.
echo '<pre>' . print_r($usernamesString, TRUE) . '</pre>';

方法2:使用MySQL函数group_concat()

构建用户名字符串

请注意使用fetch(),它只获取一个表格行。

<?php

include("db.php");

$sql = 'SELECT GROUP_CONCAT(username) AS usernames FROM members';

$statement = $odb->prepare($sql);
$statement->execute();
$fetchedData = $statement->fetch(PDO::FETCH_ASSOC);

// Just for testing: Print fetched data list.
echo '<pre>' . print_r($fetchedData, TRUE) . '</pre>';

// Build the user names string.
$usernamesString = $fetchedData['usernames'];

// Print the user names string.
echo '<pre>' . print_r($usernamesString, TRUE) . '</pre>';