Reputation: 2005
my php code is :
$q = $db->query("SELECT username FROM users LIMIT 3");
$users = array();
while($row = $db->fetchAll($q))
{
$users[] = $row;
}
foreach($users as $user)
{
echo $user['username'].'<br>';
}
and the output will be
Nilsen
Michael
Sam
Does it possible to change my output format to be Nilsen,Michael,Sam
without start foreach ?
Any idea please ?
Thank you.
Upvotes: 0
Views: 77
Reputation: 5744
Do you mean this?
$stmt = $db->query('SELECT username FROM users LIMIT 3');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$users = array_map(function($row) {
return $row['username'];
}, $rows);
print_r($users);
Upvotes: 0
Reputation: 3028
Mostly for debugging you can use like this :
$q = $db->query("SELECT username FROM users LIMIT 3");
while($row = $db->fetchAll($q))
{
print_r($row); // or below
var_dump($row);
}
The var_dump()
function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.
The print_r()
displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.
Upvotes: 0
Reputation:
$q = $db->query("SELECT username FROM users LIMIT 3");
while($row = $db->fetchAll($q))
{
print_r($row);
}
.
or
echo $row[0], $row[1], $row[2];
I wouldn't recommend this for production though, just for checking/debuging..
Upvotes: 0
Reputation: 160833
while($row = $db->fetchAll($q)) // fetchAll is wired here, but since you get the result, asume that's right
{
$users[] = $row['username'];
}
then use:
echo join(',' $users);
Upvotes: 2
Reputation: 263693
you can use GROUP_CONCAT()
and loop won't be needed on the php side.
SELECT GROUP_CONCAT(username) user_name FROM users LIMIT 3
Upvotes: 1