create array from mysql result? - php

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;

Related

how to make a mysql query and turn it into an array in php

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;
}

Create array in PHP from mysql

I think that I may be over trying things with little sleep but I am having problems creating arrays from mysql queries. I have a query like so:
$result = mysqli_query($con,"SELECT * FROM vehicles ORDER BY id");
while($row = mysqli_fetch_array($result)) {
$description = $row['description'];
$description = strtoupper($description);
$id = $row['id'];
}
I want it to create an array like so:
$v[1] = "Myarray1";
I have tried this but it does not work:
$v[ $row['id']] = $row;
Do I have to query like this:
while( $row = mysql_fetch_assoc( $result)){}
and if I do, how I do create the array as I need it?
Many thanks in advance
At no point are you creating an array here. In your loop you are simply modifying some variables that in the context you posted I cannot reason on.
If all you need, no data filtering whatsoever this will do:
$list = Array();
while( $row = mysqli_fetch_array($result) ) {
$list[] = $row;
}
[] basically 'appends' in PHP, it is an ugly mechanism but it works.
If you want to access rows per primary key ( id in your case I think ) then simply replace [] with [$row["id"]]
I'm not exactly sure of the end result you're looking for. But if you want to access the results as $row['column'], where 'column' is a column name in your MySQL database, then you need to use mysql_fetch_assoc. I think this example will help:
while (($row = mysqli_fetch_assoc($result))) {
$v[$row['id']] = $row;
}
$v[1]['description'] is the data in the column description for the record with an id=1

Php append value to an exsisting array

Hi I need to add some value-key pair to an array which is the output of mysql query. Below is the code,
$query = "select TITLE,DESCRIPTION from TABLE where ID='1234'";
$result = mysqli_query($conn, $query);
$numrows = mysqli_num_rows($result);
if($numrows>0)
{
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$myArray[] = $row;
}
}
echo json_encode($myArray);
Giving me the result like
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION."}]
Now I need to to add an another key-value pair to generate the json output like,
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION.","URL":"imgname.jpg"}]
So I added the code
$myArray["URL"]="imgname.jpg";
echo json_encode($myArray);
But giving me the output like,
{"0":{"TITLE":"Chef Special","DESCRIPTION":"Grilled Salmon and crab."},"URL":"imgname.jpg"}
Is there anything wrong with above code.
check your data with
var_dump($myArray);
and you will find, that it is a 2-dimensional array. you'd have to add your data with
$myArray[0]["URL"] = "imgname.jpg";
If you have to add after encoding it, reverse with:
$a = json_decode($myArray,true)
add a new pair of key, value with $a['URL'] = "imgname.jpg" and then encode again.

change my output format

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);

Echo the results of query based on its index

This is pretty basic but I can't seem to get it to work
I have this query
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$row_people = mysql_fetch_assoc($people);
$totalRows_people = mysql_num_rows($people);
I can echo the first result of this query with
<?php echo $row_people['name']; ?>
I could also create a loop and echo all the results.
But I really want to echo the results individually based on its index.
I have tried this, but it does not work.
<?php echo $row_people['name'][2]; ?>
Thanks for your help.
You can fetch them by their index using a WHERE clause.
$people = sprintf("SELECT name FROM people WHERE index='%d'", $index);
If you want to query all rows, you could store them into an array while looping over them:
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$totalRows_people = mysql_num_rows($people);
$rows_people = array();
while($row_people = mysql_fetch_assoc($people))
{
$rows_people[] = $row_people;
}
You might want to add the primary key to the returned fields and use it as the array index probably.
You can ORDER them by their index and then use a loop.
$people = "SELECT name FROM people ORDER by index";
You can use mysql_data_seek on the result object to seek to a particular row. E.g., to get the name value from row 2:
mysql_data_seek($people, 2);
$row_people = mysql_fetch_assoc($people);
echo $row_people['name'];
If you're doing this a lot it will be easier to gather all the rows together in a single array at the start:
$data = array();
while ($row = mysql_fetch_assoc($people)) $data[] = $row;
This way you can fetch any cells in the results trivially:
echo $data[2]['name'];

Categories