PHP Add to Multidimensional Array using mysql_fetch - php

I've looked on the web but all I can find is how to echo data from arrays, but I need to add to them. This array is multidimensional so I need to add an array to an array all the time. How do I do this?
Heres the code:
<?php
$data = array(
"contacts" => array(
array(
'id'=> "1",
'catagory'=> "LifeStyle",
'title'=> "Some Cool Title",
'url'=> "http://example.com",
),
)
);
$sql = mysql_query("SELECT * FROM magazines WHERE category = '$cat'");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$cat = $row["category"];
$title = $row["title"];
$url = $row["url"];
// add to array
// array(
// 'id'=> "$id",
// 'catagory'=> "$cat",
// 'title'=> "$title",
// 'url'=> "$url",
// ),
}
mysql_close();
echo json_encode($data);
?>

Just do this...
while($row = mysql_fetch_array($sql)){
$data['contacts'][] = $row;
}
Or this...
while($row = mysql_fetch_array($sql)){
array_push($data['contacts'], $row);
}
Then a print_r will show you your array...
print_r($data);

Instead of doing SELECT * select only the fields you want to push into the array. Something like this
<?php
$sql = mysql_query("SELECT id, category, title, url FROM magazines WHERE category = '$cat'");
while($row = mysql_fetch_array($sql)){
$data['contacts'][] = $row;
}
?>

Related

Array json from php is not output in the corect way

I'm trying to make a json output from my db in php with all of users from sql table but i don't know how to do that..i'm new with this.
I want the code to output like this.
[
{
"name": "Maybell",
"avatar": "zeldman/128.jpg",
"data": {
"company": "Alibaba",
"title": "Engineer"
}
}
]
but the my code does the following output and is not ok.
{
"name": "Maybell",
"avatar": "zeldman\/128.jpg",
"company": "alibaba"
"title": "Engineer"
}
Here is the Php code:
<?php
header("Content-type: text/json");
$db = mysqli_connect("localhost","root","","testest");
//MSG
$query = "SELECT * FROM mls_users LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$name = $row['name'];
$avatar = $row['avatar'];
$company= $row['company'];
$title= $row['title'];
}
//Return result to jTable
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['company'] = $company;
$qryResult['title'] = $title;
echo json_encode($qryResult,JSON_PRETTY_PRINT);
mysqli_close($db);
?>
Just change:
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$name = $row['name'];
$avatar = $row['avatar'];
$company= $row['company'];
$title= $row['title'];
}
//Return result to jTable
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['company'] = $company;
$qryResult['title'] = $title;
To:
//Add all records to an array
$qryResult = [];
while ($row = $result->fetch_array()) {
$qryResult[] = [
'name' => $row['name'],
'avatar' => $row['avatar'],
'data' => [
'company' => $row['company'],
'title' => $row['title'],
],
];
}
You can skip setting the intermediate variables and just add onto the $qryResult array directly.
try this:
<?php
header("Content-type: text/json");
$db = mysqli_connect("localhost","root","","testest");
//MSG
$query = "SELECT * FROM mls_users LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$users = array();
while($row = $result->mysqli_fetch_assoc()){
$users[] = [
'name' => $row['name'],
'avatar' => $row['avatar'],
'data' => [
'company' => $row['company'],
'title' => $row['title']
]
]
}
echo json_encode($users,JSON_PRETTY_PRINT);
mysqli_close($db);
?>
I changed fetch_row() to mysqli_fetch_assoc() and then actually made an array with all fetched rows. You kind of wanted to do that i can see that in comments but you didnt. Then just json encode it.
The outlining brackets [ and ] should come automatically when the array has multiple elements in it.
You are almost there, you just need to wrap it in an array and make data an array.
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
// Now make an array to hold data
$data = array();
$data['company'] = $company;
$data['title'] = $title;
// Add data to qryResult
$qryResult['data'] = $data
// Wrap qryResult in array so output will be wrapped in array
$outPutResults = array($qryResult);
echo json_encode($outPutResults,JSON_PRETTY_PRINT);
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['data']['company'] = $company;
$qryResult['data']['title'] = $title;
Try that way. You are asking for a multidimensional-array so you need to set it up as one.

Json array add onto php array

I want to acheive something simliar to this adding elements onto an array but when I use this methods two nodes get created in the json element. I only want one node with all the entires within that also can you name nodes ie Properties.
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
$data[] = $json;
}
$custom = array('name'=>'foo', 'id' => 'bar');
$data[] = $custom;
Try this code array_push is better option here,
<?php
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$temp = array();
$temp = array('name' => $row['name'], 'id' => $row['id']);
array_push($json, $temp);
}
$custom = array('name'=>'foo', 'id' => 'bar');
array_push($json,$custom);
?>

How can I format my JSON in this way?

I'm trying to output JSON in this format:
[{"name":"venue 1"}, {"name":"venue 2"}, {"name":"venue 3"}]
But it's currently coming out like this:
{"name":"venue 1"}{"name":"venue 2"}{"name":"venue 3"}
Here is my code:
query = "SELECT * FROM venues";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$arr = array(
'name'=> $row['name']
);
print json_encode($arr);
What do I need to change?
Add $arr[] intead of $arr
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$arr[] = array('name'=> $row['name'] );
}
echo json_encode($arr);
Try this:
$arr[] = array(
'name'=> $row['name']
);
Simply make an array like
$array[]["name"]="value1";
$array[]["name"]="value2";
$array[]["name"]="value3";
echo json_encode($array);
you will get the json data as:
[{"name":"value1"},{"name":"value2"},{"name":"value3"}]
which you wants. You have to make the array using looping statements according to your need.

Pulling data from MySQL into json array

I'm trying to pull data from my database using json in php. I have a few elements I need to specific then to post them on a page.
I want to "fetch" the data from mysql and return it to a json_encode. How can I do this using the SELECT method. Some had used PDO methods and other have used mysql_assoc, which confuses me.
For instance,
I have rows of: 'id' , 'title' , 'start', 'backgroundColor'...etc. along with a default value for all of them. ($array[] = "someValue = default")
I want it to export like so:
array(
'id' => 1,
'title' => "someTitle",
'start' => "2012-04-16",
'backgroundColor' => "blue",
'someValue' = > "default",
...
), ....
));
If anyone could help me with this with the best detail, I'd be awesome!
If you wanted to do this with PDO then here is an example:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=DBNAME", $username, $password);
$sql = "SELECT `id`, `title`, `time`, `start`, `backgroundColor`
FROM my_table";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
$return = [];
foreach ($result as $row) {
$return[] = [
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start'].' '.$row['time'],
'backgroundColor' => $row['backgroundColor']
];
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
You don't "fetch to a json array".
You fetch your database results into a PHP array, then convert that php array, AFTER THE FETCHING IS COMPLETED, to a json string.
e.g.
$data = array();
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
echo json_encode($data);
You can get the result from mysql,then format it to json
$array = array();
while($row = mysqli_fetch_array($result))
{
array_push($array,$row);
}
$json_array = json_encode($array);
Please check for SELECT methods here
In general it would look like this
$data = array(); // result variable
$i=0
$query = "SELECT id,title,start,backgroundColor FROM my_table"; // query with SELECT
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){ // iterate over results
$data['item'][$i]['id'] = $row['id']; // rest similarly
...
...
$i++;
}
header('Content-type: application/json'); // display result JSON format
echo json_encode(array(
'success' => true,
'data' => $data // this is your data variable
));

Assigning Values to a 2d array

I am trying to assign values from a db to a 2d array, but its only showing the last iterms.
Here is the code:
while($row = mysql_fetch_array($results)){
$MyData = array( array("Focus Area", $row["FocusArea"]),
array("Finding Title", $row["FindingTitle"]),
array("Finding Detail", $row["FindindDetail"])
);
}//End While
What am I doing wrong please help.
$MyData[] = $row;
would be enough
I'd also suggest to make a function, as getting an array from db is a very common routine.
So, you'll be able to get your data in one line,
$myData = getRows("SELECT * FROM table");
$myData = array();
while($row = mysql_fetch_array($results)){
$MyData[] = array( array("Focus Area", $row["FocusArea"]),
array("Finding Title", $row["FindingTitle"]),
array("Finding Detail", $row["FindindDetail"])
);
}//End While
this will do the trick
You're declaring a new array each time the loop runs. Declare it out of the while loop, and add the new values.
$MyData = array();
while($row = mysql_fetch_array($results)){
$MyData[] = array( array("Focus Area", $row["FocusArea"]),
array("Finding Title", $row["FindingTitle"]),
array("Finding Detail", $row["FindindDetail"])
);
}//End While

Categories