I am developing a webservice for and android app the webservice is in PHP fetching data from a MySQL database ... The problem that I am having is that some of the projects have multiple details but my code is only fetching one detail for every project. I am getting the data in JSON format.
You can check this Here
Here is my code
function requiredData(){
$db = $this->dbConnection();
//$sql = "SELECT * FROM projects JOIN project_details ON projects.project_id=project_details.project_id";
$sql = "SELECT * FROM projects";
$queryResult = $db->query($sql);
if($queryResult->num_rows > 0){
while($row = $queryResult->fetch_assoc()){
$pid = $row['project_id'];
$detailsql = "SELECT * FROM project_details WHERE project_id=$pid";
$sqlResult = $db->query($detailsql);
if($sqlResult->num_rows > 0){
while ($d = $sqlResult->fetch_assoc()){
$r = array(
"project_id" => $d['project_id'],
"project_detail" => array(
"work_done" => $d['project_detail'],
"payment_for_work" => $d['project_payment'],
"payment_status" => $d['project_payment_status'],
"detail_id" => $d['project_detail_id']
)
);
}
}
$results[$row['project_name']] = array(
"project_id" => $row["project_id"],
"project_start_date" => $row["project_start_date"],
"project_due_date" => $row["project_due_date"],
"project_currency" => $row["project_currency"],
"project_work_details" => $r
);
}
}
return $results;
}
Thanks in advance for your help
The issue is in the second while loop. You are assigning array to $r, and $r value overwrites every time.
So, I am assigning now array to an other array, So it will become 2 dimensional array, like this;
while ($d = $sqlResult->fetch_assoc()){
$r[] = array(
"project_id" => $d['project_id'],
"project_detail" => array(
"work_done" => $d['project_detail'],
"payment_for_work" => $d['project_payment'],
"payment_status" => $d['project_payment_status'],
"detail_id" => $d['project_detail_id']
)
);
}
Now you can use $r, it will have multiple details of the project.
Related
I'm building an angular application, so I have a PHP script extracting the database data into a JSON when requested.
This is what I'm using to extract the data into an array:
$values = array();
$query = "SELECT * FROM photos ORDER BY id";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
array_push($values, $row);
}
json_encode($values);
But it gives no result.
After some testing, if I change json_encode($values); to print_r($values); it actually print the table array, here an extract:
Array (
[0] => Array (
[id] => 4
[title] => Feel the Moment
[views] => 6
)
It seems the script is not creating a valid array.
$query = "SELECT * FROM photos ORDER BY id";
if ($result = $this->mysqli->query($query)) {
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = $row;
}
echo json_encode($json);
}
Your while is not executing, probably because you don't have any returned values from database.
I tested this code and it works well:
$json = array();
$json[] = array(
"id" => 1,
"category" => 'a',
"tags" => 't');
$json[] = array(
"id" => 2,
"category" => 'b',
"tags" => 'tt');
echo json_encode($json);
The result is:
[{"id":1,"category":"a","tags":"t"},{"id":2,"category":"b","tags":"tt"}]
And you'd better use mysqli_fetch_row or mysqli_fetch_assoc.
Try to debug your code. You may use var_dump($result->fetch_assoc()) to see if the query has some results.
I'm struggling trying to create a three-dimensional array from my DB, and encoding it to JSON.
My DB contains 3 tables, timeline_table, content_table and pic_table. I want the following structure for my JSON:
{"timeline:"{"content":{"pictures:"{}}}}
Here's my current PHP code:
$get = 1;
$results = mysql_query("
SELECT timeline_table.*, content_table.*, pic_table.*
FROM timeline_table
JOIN content_table
ON content_table.tl_ID = timeline_table.tl_ID
JOIN pic_table
ON pic_table.content_ID = content_table.content_ID
WHERE timeline_table.tl_ID = $get
") or die(mysql_error());
while($row = mysql_fetch_assoc($results)){
$timeline['timeline'][] = array(
'tl_ID' => $row['tl_ID'],
'tl_name' => $row['tl_name'],
'tl_date' => $row['tl_date'],
'tl_desc' => $row['tl_desc'],
);
$timeline['timeline']['content'][] = array(
'content_ID' => $row['content_ID'],
'tl_ID' => $row['tl_ID'],
'content_time' => $row['content_time'],
'content_date' => $row['content_date'],
'content_title' => $row['content_title'],
'content_content' => $row['content_content'],
'content_category' => $row['content_category'],
'content_mapLat' => $row['content_mapLat'],
'content_mapLng' => $row['content_mapLng'],
'content_zoomLvl' => $row['content_zoomLvl'],
);
$timeline['timeline']['content']['pictures'][] = array(
'pic_ID' => $row['pic_ID'],
'content_ID' => $row['content_ID'],
'pic_path' => $row['pic_path'],
'pic_desc' => $row['pic_desc'],
'pic_link' => $row['pic_link']
);
}
echo stripslashes(json_encode($timeline));
}
I have also tried with 1 query for each table, and using 3 while loops to fill the array. I believe one query is the better way to go, but please correct me if I'm wrong. This php gives me the following JSON:
{
"timeline":{
"0":{
"tl_ID":"1",
"tl_name":"Tidslinje 1",
"tl_date":"2013-01-16",
"tl_desc":"Test av tl_table"
},
"content":{
"0":{
"content_ID":"1",
"tl_ID":"1",
"content_time":"16:00:00",
"content_date":"2013-01-17",
"content_title":"Test",
"content_content":"Test content number one.",
"content_category":"test",
"content_mapLat":null,
"content_mapLng":null,
"content_zoomLvl":null
},
"pictures":[
{
"pic_ID":"1",
"content_ID":"1",
"pic_path":"http://i.imgur.com/F6RmDFt.jpg",
"pic_desc":"katt",
"pic_link":"http://i.imgur.com/F6RmDFt.jpg"
},
{
"pic_ID":"3",
"content_ID":"3",
"pic_path":"http://i.imgur.com/POum7eK.jpg",
"pic_desc":"seamonster",
"pic_link":"http://i.imgur.com/POum7eK.jpg"
}
]
}
}
}
All pictures regardless of content_ID comes in one array, and if I add more content, contents with ID 2,3 etc comes under the picture array. I want the pictures in arrays under the content_ID they belong to, and the content under the timeline they belong to. I also want the array keys to be "timeline", "content" and "pictures", instead of integers.
Hopefully this is understandable, any help is greatly appreciated!
EDIT: Solved!
$get = 1;
$result = mysql_query("
SELECT t.tl_ID, t.tl_name, t.tl_date, t.tl_desc, c.content_ID, c.content_time, c.content_date, c.content_title, c.content_content, c.content_category, p.pic_ID, p.pic_path, p.pic_desc, p.pic_link
FROM timeline_table t
LEFT JOIN content_table c ON t.tl_ID = c.tl_ID
LEFT JOIN pic_table p ON c.content_ID = p.content_ID
WHERE t.tl_ID = $get
ORDER BY t.tl_ID, c.tl_ID, p.content_ID
") or die(mysql_error());
$jsonData = array();
$tl_ID = 0;
$content_ID = 0;
$timelineIndex = -1;
$contentIndex = -1;
while($row = mysql_fetch_assoc($result)){
if($tl_ID != $row['tl_ID']){
$timelineIndex++;
$contentIndex = -1;
$tl_ID = $row['tl_ID'];
$jsonData[$timelineIndex]['tl_ID'] = $row['tl_ID'];
$jsonData[$timelineIndex]['tl_name'] = $row['tl_name'];
$jsonData[$timelineIndex]['tl_date'] = $row['tl_date'];
$jsonData[$timelineIndex]['tl_desc'] = $row['tl_desc'];
$jsonData[$timelineIndex]['content'] = array();
}
if($content_ID != $row['content_ID']){
$contentIndex++;
$content_ID = $row['content_ID'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_ID'] = $row['content_ID'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_time'] = $row['content_time'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_date'] = $row['content_date'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_title'] = $row['content_title'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_content'] = $row['content_content'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_category'] = $row['content_category'];
$jsonData[$timelineIndex]['content'][$contentIndex]['pictures'] = array();
}
$jsonData[$timelineIndex]['content'][$contentIndex]['pictures'][] = array(
'pic_ID' => $row['pic_ID'],
'pic_path' => $row['pic_path'],
'pic_desc' => $row['pic_desc'],
'pic_link' => $row['pic_link']
);
}
echo stripslashes(json_encode($jsonData));
}
Edited, try this one:
$timeline['timeline'][] = array(
'tl_ID' => $row['tl_ID'],
'tl_name' => $row['tl_name'],
'tl_date' => $row['tl_date'],
'tl_desc' => $row['tl_desc'],
'content' => array(
'content_ID' => $row['content_ID'],
'tl_ID' => $row['tl_ID'],
'content_time' => $row['content_time'],
'content_date' => $row['content_date'],
'content_title' => $row['content_title'],
'content_content' => $row['content_content'],
'content_category' => $row['content_category'],
'content_mapLat' => $row['content_mapLat'],
'content_mapLng' => $row['content_mapLng'],
'content_zoomLvl' => $row['content_zoomLvl'],
'pictures' => array(
'pic_ID' => $row['pic_ID'],
'content_ID' => $row['content_ID'],
'pic_path' => $row['pic_path'],
'pic_desc' => $row['pic_desc'],
'pic_link' => $row['pic_link']
);
);
);
I have an php array with presentation as follow:-
<?php
$ads = array();
$ads [] = array(
'name' => 'Apple',
'duration' => '3',
'price' => "$5"
);
$ads [] = array(
'name' => 'Orange',
'duration' => '2',
'price' => "$10"
);
$ads [] = array(
'name' => 'Banana',
'duration' => '5',
'price' => "$6"
);
and then, I would like to replace the static data with dynamic data from database:-
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
while($record = mysql_fetch_array($result))
{
$fruit_id = $record['fruit_id'];
$fruit_name = $record['fruit_name '];
$fruit_price= $record['fruit_price'];
$fruit_duration= $record_approve['fruit_duration'];
}
Actually, how shall I combine the 2 presentations together? Thanks!
If you want to get a similar structure as the one that you have in the first example, you can modify your second to create a new array and append it to an existing $ads array.
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[] = array(
'name' => $record['fruit_name'],
'price' => $record['fruit_price'],
'duration' => $record['fruit_duration']);
}
iteration over result can be modified (provided only the required attributes are fetched in the query)
$fruit = array();
while($record = mysql_fetch_array($result))
{
$fruit[] = $record;
}
may be you could use array_merge
$result = array();
$result = array_merge($ads,$fruit);
So, you want to populate your "ads" array with information from the database? It seems fairly counterintuitive seeing as mysql_fetch_array already returns a perfectly adequate associative array, but here you go:
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[] = array (
'name' => $record['fruit_name'],
'price' => $record['fruit_price'],
'duration' => $record['fruit_duration']
);
}
If
the initial array is not just an example, but default data that you might overwrite with the db data, and
the fruit name is unique (a primary key of sorts)
then you should set the array key of the main array to that of the fruit name, so that if the db has a different value, it will automatically get overwritten but otherwise left alone. Like so:
$ads ['Apple'] = array(
'duration' => '3',
'price' => "$5"
);
$ads ['Orange'] = array(
'duration' => '2',
'price' => "$10"
);
$ads ['Banana'] = array(
'duration' => '5',
'price' => "$6"
);
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[$record['fruit_name']]['price'] = $record['fruit_price'];
$ads[$record['fruit_name']]['duration'] = $record['fruit_duration'];
}
Now, if 'Apple' is in the db, the price and duration get overwritten, but otherwise, it stays where you set it before the query.
You could go a step further and have both the price and duration returned by the query checked for an empty value (Null, "", 0), and only set the value if it is not empty, etc. But that is more a of business logic decision.
$feeds = array();
$query = "SELECT * FROM actions WHERE user_id = '$user_id'";
$result = mysql_query($query);
while ($info = mysql_fetch_array($result)) {
$feeds[][$info['date']] = array("feed" => array($info['ID'] => $user_id));
}
$query = "SELECT * FROM follows WHERE user_id = '$id'";
$result = mysql_query($query);
while ($info = mysql_fetch_array($result)) {
$feeds[][$info['date']] = array("follow" => $info['user_id']);
}
I would like to sort that $feeds array in date format (Y-m-d H:i:s) using [$info['date']] key
How can i do that ?
thanks
EDIT:
example of what i want to see as result is
$feeds = array(
0 => array(
'<date>' => array("feed" => array("feed_id" => "user_id"));
),
1 => array(
'<date>' => array("follow" => "user_id" );
),
);
I want to group/sort them in DATE key and do sth depends on if it is FEED or FOLLOW
The best way is to do it in database (faster)!
But if you want do it in PHP, your need uksort (for sorting) + foreach (for grouping) I think
I am having trouble at creating a specific array.
What i want is to pull the info for my members (from mysql database) and then store them to an array.
The array should be like this:
$members = array(
'John' => array('avatar' => '/images/avatar/ji.jpg', 'country' => 'uk.'),
'Nick' => array('avatar' => '/images/avatar/nick.jpg', 'country' => 'italy.'),
);
etc..
so i pull the name,avatar url and country from the db and then i store them in to the previous array.
My question is, how could i create this array?
Thanks in advance!
About creating an array at php.
Something like this should work:
$members = array();
$q = mysql_query("SELECT name , avatar, country from table");
while($row = mysql_fetch_assoc($q)){
$array = array("avatar" => $row['avatar'] , "country" => $row['country']);
$members[$row['name']] = $array;
}
Using PDO:
$members = array();
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$sql = "SELECT name, avatar, country FROM members";
foreach ($conn->query($sql) as $row) {
$temp = array('avatar' => $row['avatar'], 'country' => $row['country']);
$members[$row['name']] = $temp;
}