如何从示例
中的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;
?>
答案 0 :(得分:0)
请注意使用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>';
请注意使用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>';