I am learning Api development where i want to retrieve data from two tables
First table (items) contains:
id, feed_id, title, author, content
Second table (feeds):
feed_id,title,url
I want to get Json response like:
{
- stories :
[
id
feed_id {
title,
url
}
title
author
]
}
My PHP function to retrieve story biased on id is like:
$app->get('/stories/:id', 'authenticate', function($story_id) {
$response = array();
$result = Database::get('db')->table('items')
->eq('rowid', $story_id)
->findOne();
//$response["error"] = false;
if ($result != NULL) {
$response['stories'] = array(
'id' => $result["id"],
'feed_id' => $result["feed_id"],
'title' => $result["title"],
'isBreaking' => $result['isBreaking'],
'author' => $result['author'],
'updated' => $result["updated"],
'url' => $result['url'],
'content' => $result["content"]);
echoRespnse(200, $response);
}
else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
The result i get is like:
{
- "stories": [
{
id
feed_id
title
url
}
]
}
How can i retrieve data from the second tablet (feeds) biased on feed_id and get the data into sub array?
as #MikeBrant mentioned you have to use join between two tables to retrieve correct data. the plain query will be something like this:
select items.id, items.title, items.author, items.content, feeds., feeds.title as feed_title, feeds.url from items left join feeds on items.feed_id = feeds.feed_id
and then change your $response['stories'] like this:
$response['stories'] = array(
'id' => $result["id"],
'feed_id' => array(
'title' => $result["feed_title"],
'url' => $result["url"]
),
'title' => $result["title"],
.
.
.
);
you get the idea :)
Related
I am new with coding and I just can't seem to get my head around this. A little help or tip is much appreciated.
Basically I want an array with Questionnaires, which consist of id, name and a sub array of questions. Questions also consist of id and name.(1 Questionnaire can have multiple questions)
Something like this is what I am looking for:
[{Questionnaires{id:x, name:x, questions:{id:x, name:x},{id:x2, name:x2}}]
This is my query
SELECT questionnaires.id QuestionnaireId, questionnaires.title QuestionnaireTitle, questions.id QuestionId, questions.text Question
FROM questionnaires INNER JOIN questionnaireshasquestions qa ON qa.idQuestionnaire = questionnaires.id
INNER JOIN questions ON questions.id = qa.idQuestion
And my PHP Code:
while ($row = $conn->fetch()) {
if (!isset($data['questionnaires'][$row['QuestionnaireId']])) {
$data['questionnaires'][] = array(
'id' => $row['QuestionnaireId'],
'title' => $row['QuestionnaireTitle'],
'questions' => array(
'id' => $row['QuestionId'],
'text' => $row['Question']
)
);
} else {
$data['questionnaires'][$row['QuestionnaireId']][] = array(
'questions' => array(
'id' => $row['QuestionId'],
'text' => $row['Question']
)
);
}
The JSON array I get with this is in a wrong/incorrect format:
{"questionnaires":[{"id":"1","title":"Are you hungry?","questions":{"id":"1","text":"How is your passion? "}},{"id":"1","title":"Are you hungry?","questions":{"id":"2","text":"Do you drink?"}},{"id":"2","title":"How are you feeling?","questions":{"id":"1","text":"How is your passion? "},"0":{"questions":{"id":"3","text":"Do you like fish?"}}},{"id":"5","title":"Is testing working?","questions":{"id":"4","text":"How is the testing?"}}]
As you can see, it repeats the same Questionnaire for each Question within...
I hope I explained well what I am trying to do here :)
Your collection method was a bit "broken".
This should work:
while ($row = $conn->fetch()) {
$id = $row['QuestionnaireId'];
if (!isset($data['questionnaires'][$id])) {
// First time we get this "QuestionnaireId" -
// define "container" that collects the related questions.
$data['questionnaires'][$id] = [
'id' => $row['QuestionnaireId'],
'title' => $row['QuestionnaireTitle'],
'questions' => [],
];
} else {
// Already got this "container" -
// put the question into the collection.
$data['questionnaires'][$id]['questions'][] = [
'id' => $row['QuestionId'],
'text' => $row['Question']
];
}
}
How to join Product and Product Variants to get every variant with product name. I'm getting all variants but my loop repeating product name each time with product variant.
My code is:
public function viewAllProducts($user_id){
$SelectProducts_Query = mysqli_query($this->conn, "SELECT smpr.product_id, smpr.user_id, smpr.product_name, smpr.product_sizes, smpr.product_photo, smpr.product_created, smpr.product_updated, smpq.quantity_id, smpq.quantity_product_id, smpq.quantity_user_id, smpq.quantity_available, smpq.quantity_price, smpq.quantity_cost, smpq.quantity_size_name FROM ssm_products_quantity as smpq inner join ssm_products as smpr on smpq.quantity_product_id=smpr.product_id WHERE smpr.user_id = $user_id order by smpr.product_id DESC");
if($SelectProducts_Query){
while($view_all_products = mysqli_fetch_array($SelectProducts_Query)){
$view_all_products_details[] = array(
"product_id" => $view_all_products["product_id"],
"product_name" => $view_all_products["product_name"],
"product_photo" => $view_all_products["product_photo"],
"product_sizes" => $view_all_products["product_sizes"],
"product_created_date" => $view_all_products["product_created"],
"product_updated_date" => $view_all_products["product_updated"],
"sizes" => array(
"size_id" => $view_all_products["quantity_id"],
"size_product_id" => $view_all_products["quantity_product_id"],
"size_available_id" => $view_all_products["quantity_available"]
)
);
}
return $view_all_products_details;
}else{
return $view_all_products_details = "false";
}
}
right now I'm getting records like this:
I want to get records like this:
{
"error":false,
"products_detail":[
{
"product_id":"24",
"product_name":"Miror",
"product_photo":"product_images\/1-dummy-17-07-11-10-26-06.jpg",
"product_sizes":"2",
"product_created_date":"2017-07-11 13:26:06",
"product_updated_date":"0000-00-00 00:00:00",
"sizes":{
"size_id":"1",
"size_product_id":"24",
"size_available_id":"50"
},{
"size_id":"2",
"size_product_id":"24",
"size_available_id":"20"
}
},
{
"product_id":"25",
"product_name":"Pipes",
"product_photo":"product_images\/1-pipes-17-07-11-10-22-08.jpg",
"product_sizes":"2",
"product_created_date":"2017-07-11 13:26:06",
"product_updated_date":"0000-00-00 00:00:00",
"sizes":{
"size_id":"3",
"size_product_id":"25",
"size_available_id":"20"
},{
"size_id":"4",
"size_product_id":"25",
"size_available_id":"20"
}
}
]
}
Any solution for me?
use your product id as an array index
try this:
public function viewAllProducts($user_id){
$SelectProducts_Query = mysqli_query($this->conn, "SELECT smpr.product_id, smpr.user_id, smpr.product_name, smpr.product_sizes, smpr.product_photo, smpr.product_created, smpr.product_updated, smpq.quantity_id, smpq.quantity_product_id, smpq.quantity_user_id, smpq.quantity_available, smpq.quantity_price, smpq.quantity_cost, smpq.quantity_size_name FROM ssm_products_quantity as smpq inner join ssm_products as smpr on smpq.quantity_product_id=smpr.product_id WHERE smpr.user_id = $user_id order by smpr.product_id DESC");
if($SelectProducts_Query){
while($view_all_products = mysqli_fetch_array($SelectProducts_Query)){
$pid = $view_all_products["product_id"];
//check the array for product with id is already exists,
//if not then add the data to array[pid] without the sizes
if(!isset($view_all_products_details[$pid]){
$view_all_products_details[$pid] = array(
"product_id" => $pid,
"product_name" => $view_all_products["product_name"],
"product_photo" => $view_all_products["product_photo"],
"product_sizes" => $view_all_products["product_sizes"],
"product_created_date" => $view_all_products["product_created"],
"product_updated_date" => $view_all_products["product_updated"]
);
}
//add the array "sizes" as multidimensional array
//you can set the size_id as index too but i think it is not necessary
$view_all_products_details[$pid]["sizes"][] = array(
"size_id" => $view_all_products["quantity_id"],
"size_product_id" => $view_all_products["quantity_product_id"],
"size_available_id" => $view_all_products["quantity_available"]
);
}
return $view_all_products_details;
}else{
return $view_all_products_details = "false";
}
}
I want to create a tree view which fetching
data from Database and after that
order it by parent field
So table fields are included :
product_category_id
product_category_parent_id
product_category_name
the record that is been mentioned
by name " product_category_parent_id"
is 0 without any root and when it wish have any
ID code / number , parent Id should come in this palce
so structure of the table must be sent to the
View :
<ul><li><ul><li></li></ul></li></ul>
There is an example how to create CTreeView
private function generateTree($models)
{
$data = array();
foreach ($models as $category) {
$data[$category->id] = array(
'id' => $category->id,
'text' => ''.$category->category_name.'',
);
foreach ($category->goods as $item) {
$data[$category->id]['children'][$item->id] = array(
'id' => $item->id,
'text' => ''.$item->article.'',
'expanded' => false,
);
}
}
return $data;
}
In view
$this->widget('CTreeView', array('data' => $data,'persist'=>'cookie'));
My table looks like:
id | title | link | kind
------------------------
1 link1 http one
4 link2 http two
2 link9 http one
I want to give back a JSON Array (JSON parsing is not the problem!) which looks like:
one
- link1, http
- link9, http
two
- link2, http
The kind-colum is dynamic so I do not know the actual string. (But it is never (null)!)
What I have:
$links = array();
while($row = mysql_fetch_object($result)) {
$link = array(
'title' => $row->title,
'link' => $row->link,
'kind' => $row->kind
);
$links[] = $link;
}
echo json_encode($links);
That's one array with all columns for each element.
Use $row->kind as an index into the top level array.
$kinds = array('one' => 1, 'two' => 2, ...etc...);
$links = array();
while($row = mysql_fetch_object($result)) {
$link = array(
'title' => $row->title,
'link' => $row->link
);
$links[$kinds[$row->kind]][] = $link;
}
echo json_encode($links);
You can do this in MySQL query:
SELECT CONCAT("[",
GROUP_CONCAT(
CONCAT("{".kind.":'",title ,"'"),
CONCAT(",".kind.":'",link),"'}")
)
,"]") AS json
FROM table_name;
Sorry for bad english and bad title!
I have the table "post"
id title
1 test Thread
2 hello
3 just
so have "tags"
tagid tagname
1 test
2 russia
3 new site
so have a post_tags
tagid postid
1 1
2 1
3 1
I need an array from var_dump next below:
$posts = array(
1 => array(
'title' => 'test Thread',
'tags' => array(
'test', 'russia', 'new site',
),
),
2 => array(
'title' => 'hello',
'tags' => NULL
),
3 => array(
'title' => 'just',
'tags' => NULL
),
)
I trying do it, but i getting not that what i want.
SELECT `post`.`id`, `post`.`title`, `tags`.`tagname` FROM `post`
LEFT JOIN `post_tags` ON `post_tags`.`tagid` = `post`.`id`
LEFT JOIN `tags` ON `post_tags`.`tagid` = `tags`.`tagid`
I getting in SQL next following:
id title tagname
1 test Thread test
1 test Thread russia
1 test Thread newsite
2 hello NULL
3 just NULL
PHP
$query = mysql_query("SELECT `post`.`id`, `post`.`title`, `tags`.`tagname` FROM `post`
LEFT JOIN `post_tags` ON `post_tags`.`tagid` = `post`.`id`
LEFT JOIN `tags` ON `post_tags`.`tagid` = `tags`.`tagid`");
$posts = array();
while ($row = mysql_fetch_assoc($query))
{
$posts[] = $row;
}
var_dump($posts);
Thank you!!!
The query is fine. You just need some logic in your loop:
while ($row = mysql_fetch_assoc($query))
{
if (isset($posts[$row['id']])) {
$posts[$row['id']]['tags'][] = $row['tagname'];
}
else {
$posts[$row['id']] = array(
'title' => $row['title'],
'tags' => $row['tagname'] === null ? null : array($row['tagname'])
);
}
}
If you have already seen a row with the same post id then all you want from the current row is the tag name (so add this to the "tags" array). If it's the first time a row with this post id is seen just add it to $posts, being a little careful to set "tags" to either null or an array with one element.
you cannot get a multi-dimensional arrays back from a mysql database. you must do your own post processing to the results if you want it in that form. Something like this maybe?
$posts = array();
while ($row = mysql_fetch_assoc($query))
{
if (!isset($posts[$row['id']])) {
$posts[$row['id']] = array();
$posts[$row['id']]['title'] = $row['title'];
$posts[$row['id']]['tags'] = array();
}
if ($row['tagname'] != null) $posts[$row['id']]['tags'][] = $row['tagname'];
}
Try this:
while ($row = mysql_fetch_assoc($query))
{
if( !isset( $posts[$row["id"]] ) ) {
$posts[ $row["id"] ] = array( "title" => $row["title"], "tags" => array() );
}
array_push( $posts[ $row["id"] ][ "tags" ], $row["tagname"] );
}
I can't debug it, so tell me if you get any errors