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.
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);
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
MySQL GROUP_CONCAT()
$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..
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.
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);
Related
if I have a query that looks like this in php...
if ($result3 = $connuser->query("SELECT * FROM devices WHERE uid='".$username."'")){
}
How can I turn $result3 into an array?
Also, separate question, I tried doing
echo $result3;
but it doesn't work. Is there a way to view $result3 so I can see what it looks like?
You can do:
$rows = [];
while($row = mysqli_fetch_array($result3))
{
$rows[] = $row;
}
I'm trying to create an array(); from the mysql results/query.
The Array OUTPUT should look exactly like this:
{"1":{"info":"Rooz","lat":51.503363,"lng":-0.127625},
"2":{"info":"Michelle","lat":51.503343,"lng":-0.127567}}
So I tried to do it this:
$sql = "SELECT id, name, lat, lng FROM positions ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
$testLocs = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$testLocs[] = $row;
}
print_r(json_encode($testLocs));
but the OUTPUT of the code above is like this:
[{"id":"1","name":"Rooz","lat":"51.5033630","lng":"-0.1276250"},{"id":"2","name":"Michelle","lat":"51.503343","lng":"-0.127567"}]
I have no idea how to achieve the output that I want in an array.
Could someone please advise on this?
any help would be appreciated.
Change
$testLocs[] = $row;
to
$testLocs[$row["id"]] = array("info"=>$row["name"], "lat"=>$row["lat"], "lng"=>$row["lng"]);
Addition to #Sean's answer: You could also use (array) $row instead of create the array manually with every key:
$testLocs[$row["id"]] = (array) $row;
If you change your query in the future, you don't have to change this line.
PHP arrays are not built in a distinct way from JSON objects:
$testLocs[$row["id"]] = $row;
If you purposely want to exclude the $id property from $row you can remove it from the $row array first.
$id = $row["id"];
unset($row["id"]);
$testLocs[$id] = $row;
I believe I am using the PDO fetch functions completely wrong. Here is what I am trying to do:
Query a row, get the results, use a helper function to process the results into an array.
Query
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$qr = $q->fetchAll(PDO::FETCH_ASSOC);
if ($qr->rowCount() > 0){
foreach($qr as $row){
$names[$row['id']] = buildArray($row);
}
return $names;
}
}
My custom array building function
function buildArray($row){
$usernames = array();
if(isset($row['id'])) $usernames['id'] = $row['id'];
if(isset($row['name'])) $usernames['name'] = $row['name'];
}
I'm actually getting exactly what I want from this, but when I echo inbetween I see that things are looping 3 times instead of once. I think I am misusing fetchAll.
Any help appreciated
If you're going to build a new array, there's not much point in having fetchAll() build an array. Write your own fetch() loop:
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$names = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$names[$row['id']] = $row;
}
return $names;
}
There's also no need for buildArray(), since $row is already the associative array you want.
$result = mysql_query("SELECT * FROM Race");
$rows = mysql_num_rows($result);
for ($i = 0 ; $i < $rows ; ++$i)
{
$row = mysql_fetch_row($result);
echo $row[0];
}
above is probably an awkward method but it'll print out all datas stored in first column, which is good but now, I want to store each one of them into an array...
I tried
$array[$i]=$row[0];
and echoed it out, but it just prints"Array"...
I tried
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
...which does the same as code written before, i guess, since it too just print "Array".
Please help! Thank you!!
Do you use simple echo $array;? It's wrong. You can't output array this way.
Use this:
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
foreach($item in $array) {
echo $item."<br>"; // and more format
}
If you want to watch array contents without any format use (e.g. for debugging) print_r or var_dump:
print_r($array);
var_dump($array);
Advice: better to use assoc array.
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row['raceid'];
}
Advanced advice: better to use PDO and object results.
You SQL code will be invulnerable to SQL injections
Code will be more modern and readable.
I am looking to create an array of data to be pass to another function that is populated from a database query and am not sure how to do this.
$dataArray[0][1];
$qry = mysql_query("SELECT Id, name FROM users");
while($res = mysql_fetch_array($qry)) {
$dataArray[$res['Id']][$res['name']]
}
Thanks in advance.
This would look better
$dataArray = array();
$qry = mysql_query("SELECT Id, name FROM users");
while($res = mysql_fetch_array($qry)) {
$dataArray[$res['Id']] = $res['name'];
}
you can take a look at the PHP manual how to declare and manipulate arrays.
The below code sniper is very handy...
$select=" WRITE YOUR SELECT QUERY ";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
Thanks