json_encode result from sql database - php

Database:
id
strDomain
1
x.com
2
y.com
3
z.com
$domainSettings = array();
$db_domainList = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;");
foreach($db_domainList as $row) {
$domainSettings = array($row->strDomain);
}
$result = array('allowedDomains' => $domainSettings);
echo json_encode($result, JSON_FORCE_OBJECT);
Current output: {"allowedDomains":{"0":"x.com"}}
I need output similar to this: {"allowedDomains":"x.com","y.com","z.com"}
Output of echo json_encode($db_domainList);:
[{"strDomain":"x.com"},{"strDomain":"z.com"},{"strDomain":"y.com"}]

If I understand your question correctly considering the needed output is invalid, this code should do the trick.
$db_domainList = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;");
$domainSettings = []; //Just incase $db_domainList is empty
foreach($db_domainList as $row) {
$domainSettings[] = $row->strDomain;
}
$result = array('allowedDomains' => $domainSettings);
echo json_encode($result);
Note that I have removed JSON_FORCE_OBJECT flag since you are asking for an output that contains and array.
The output of the above code should look like this which is very close to what you are looking for.
{
"allowedDomains": [
"x.com",
"y.com",
"z.com"
]
}

If I don't misunderstand you requirement, then you can do this way-
$db_domainList = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;");
foreach($db_domainList as $row) {
$domainSettings[] = $row->strDomain;
}
$result = array('allowedDomains' => implode(',',$domainSettings));
echo json_encode($result, JSON_FORCE_OBJECT);

Related

Array for a SQL database using PHP

Can someone please help? I'm new to PHP and struggling to make this bit of code to work. For example I have a sql database table with the following schema and data:
Type....rent_price
a..........100
b..........200
c..........300
I want to be able to echo say, "a", in one section and "200" in another. The following code will display "a" but then I can't seem to get it to display anything from the rent_price column using a second array.
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row['type']);
for ($set1 = array (); $row = $result->fetch_assoc(); $set1[] =$row['rent_price']);
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
You loop through the results twice, without resetting. Try to loop only once:
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
$set = array ();
$set1 = array ();
while ($row = $result->fetch_assoc())
{
$set[] = $row['type'];
$set1[] =$row['rent_price'];
}
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
Depending on what you mean by '"a" in one section and "200" in another', you may be able to forgo creating the intermediate arrays and just print the values from your query as you fetch them. Two cells in a table row, for example:
while ($row = $result->fetch_assoc()) {
echo "<tr><td>$row[type]</td><td>$row[rent_price]</td></tr>";
}
your data is in the first element of array
$set1[0]
but youre probably better off maintaining the naming throughout
$results = array();
while ($row = $result->fetch_assoc()){
$results[] = $row;
}
foreach ($results as $result){
echo $result['type'];
echo $result['rent_price'];
}
OR
$results = array();
while ($row = $result->fetch_assoc()){
$results['types'][] = $row['type'];
$results['rent_prices'][] = $row['rent_price'];
}
foreach ($results['types'] as $type){
echo $type;
}
foreach ($results['rent_prices'] as $rent_price){
echo $rent_price;
}

How to combine two or more mysql array in one

I have two table that has multiple rows. I want to combine those two tables rows into one long array which will be identified as one array
I wrote this code
$posts_sql = $db->query("SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5");
$posts_all = $db->fetch_all($posts_sql);
foreach($posts_all as $key => $posts_row){
$users_sql = $db->query("SELECT username,firstname,lastname,avatar FROM users WHERE username = '".$posts_row['submitter']."'");
$users_all = $db->fetch_assoc($users_sql);
$data[] = $posts_row;
$data[] = $users_all;
}
echo json_encode($data);
It makes duplicate arrays doesn't right...
That's how my result show
[{
"id":"39",
"hash":"070fcc8e73ba5f549f87",
"post":"hello\n",
"files":"",
"location":",
"GB","status":"1",
"position":"dabblos",
"submitter":"dabblos",
"source":"text",
"ip":"37.130.227.133",
"stamp":"1390197699"
},
{
"username":"dabblos",
"firstname":"dabb",
"lastname":"los",
"avatar":"no_avatar.png"
}]
please help me make it just one long array
I would like to see the output looks like this
{
"id":"39",
"hash":"070fcc8e73ba5f549f87",
"post":"hello\n",
"files":"",
"location":",
"GB","status":"1",
"position":"dabblos",
"submitter":"dabblos",
"source":"text",
"ip":"37.130.227.133",
"stamp":"1390197699"
"username":"dabblos",
"firstname":"dabb",
"lastname":"los",
"avatar":"no_avatar.png"
}
look at this,i have taken example values, it is working fine as you wanted
$arr=array(array("abc"=>"1","def"=>"2"),array("abcc"=>"11","deff"=>"22"));
echo json_encode($arr);
$final = array();
foreach($arr as $item) {
$final = array_merge($final, $item);
}
print_r($final);
output
[{"abc":"1","def":"2"},{"abcc":"11","deff":"22"}]//json_array
Array ( [abc] => 1 [def] => 2 [abcc] => 11 [deff] => 22 )//final array
UPDATE
json_encode the final array and you'll get the desired result
echo json_encode($final);
output
{"abc":"1","def":"2","abcc":"11","deff":"22"}
Untested:
$posts_sql = $db->query("SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5");
$posts_all = $db->fetch_all($posts_sql);
foreach($posts_all as $key => $posts_row) {
$users_sql = $db->query("SELECT username,firstname,lastname,avatar FROM users WHERE username = '".$posts_row['submitter']."'");
$users_all = $db->fetch_assoc($users_sql);
$data[] = $posts_row;
foreach($users_all as $user)
$data[] = $user;
}
}
echo json_encode($data);
// when you use json_decode use the 'true' flag as in
// $decodedJson = json_decode($json, true);
Merge them before you json_encode them:
$data[] = $posts_row;
$data2[] = $users_all;
$result = array_merge($data,$data2);
echo json_encode($result);

converting php array into a single JSON object

I am having an issue with how I am converting my php array into a JSON object. No matter what I try, I either print everything out as multiple objects or it comes out as null.Wrapping it in pre tags, here is the closest that I got it:
My code:
$content = mysqli_query($dbcon,
"SELECT title, last_name AS lastname
FROM revision, field_last_name
WHERE vid = entity_id;"
);
echo "<pre>";
while($row = mysqli_fetch_array($content))
{
print json_encode($row);
print '<br/>';
}
echo "</pre>";
My output:
{"0":"John Apple","title":"John Apple","1":"Apple","lastname":"Apple"}
{"0":"Kumar Patel","title":"Kumar Patel","1":"Patel","lastname":"Patel"}
{"0":"Michaela Quinn","title":"Michaela Quinn","1":"Quinn","lastname":"Quinn"}
{"0":"Peyton Manning","title":"Peyton Manning, MD","1":"Manning","lastname":"Manning"}
{"0":"John Doe","title":"John Doe","1":"Doe","lastname":"Doe"}
{"0":"Jane Lee","title":"Jane Lee","1":"Lee","lastname":"Lee"}
{"0":"Dan McMan","title":"Dan McMan","1":"McMan","lastname":"McMan"}
{"0":"Yu Win","title":"Yu Win","1":"Win","lastname":"Win"}
My two questions are:
1) Why is there a "0":"John Apple" and a "1":"Apple" when all I want is "title":"John Apple" and "lastname":"Apple" in my object?
2) Why is everything displaying as multiple objects?
Thanks!
---EDIT---
$arr = array()
echo "<pre>";
while($row = mysqli_fetch_assoc($content))
{
$arr[] = $row;
}
print $arr;
echo "</pre>";
field_last_name is your table name? can you distinguish each column name prefix by table name like revision.title in your query and get all data in a single array and then json_encode it?
$content = mysqli_query($dbcon,
"SELECT title, last_name AS lastname
FROM revision, field_last_name
WHERE vid = entity_id;"
);
$arr = array();
echo "<pre>";
while($row = mysqli_fetch_assoc($content))
{
$arr[] = $row;
}
print_r(json_encode($arr));
echo "</pre>";
Change this:
while($row = mysqli_fetch_array($content))
{
print json_encode($row);
print '<br/>';
}
To this:
$row = mysqli_fetch_assoc($content);
json_encode($row);
...because you're printing out multiple objects. If you want a single object which is an array, you need to append the results of mysql_fetch_assoc (see other answer covering field names vs positions) to an array, then json_encode the array in one shot. Example:
$myarray = array();
while($row = mysqli_fetch_assoc($content))
{
$myarray[] = $row;
print '<br/>';
}
print json_encode($myarray);

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

JSON output using PHP

HI i need to output a JSON object for consuming in iphone
i am able to output like
{"feed":{"id":"1","player":"player1"}}
{"feed":{"id":"1","player":"player2"}}
{"feed":{"id":"2","player":"player3"}}
The code :
$query = "SELECT id,player FROM MyVideos";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$players[] = array();
if(mysql_num_rows($result)){
while($player = mysql_fetch_assoc($result)){
$players[] = array('player'=>$player);
echo json_encode(array("feed"=>$player));
}
}
But i need to output some thing like this
{"feed":
{"id":"1","player":"player1"},
{"id":"1","player":"player2"},
{"id":"2","player":"player3"}
}
Can anyone please help me with this.
Thanks,
The output you posted isn't valid JSON, you need to put brackets around the items in feed:
{"feed": [
{"id":"1","player":"player1"},
{"id":"1","player":"player2"},
{"id":"2","player":"player3"}
]}
You should loop through your results and build an array of your feed items, and then output it all at once, like this:
$feed_items = array();
if (mysql_num_rows($result)) {
while ($player = mysql_fetch_assoc($result)){
$feed_items[] = $player;
}
}
echo json_encode(array("feed" => $feed_items));

Categories