I am trying to display ALL blogs regardless of whether there are comments associated with it or not BUT I have 1 problem as these are as follows:
Not all fields from the COMMENTS TABLE and ENTRY TABLE are displayed (seems like if there is a duplicate field name it is not displayed, however, as you can see, I use the full field names eg. tablename.fieldname)
Here is my MODEL:
class A_User_Blog_Comments_model extends CI_Model {
public function get_blog($id) {
$this->db->select('
entry.user_id,
entry.entry_id,
entry.entry_name,
entry.entry_body,
entry.status,
entry.created_timestamp,
entry.updated_timestamp,
comments.id,
comments.comment,
comments.user_id,
comments.blog_id,
comments.status,
comments.created_timestamp,
comments.updated_timestamp
');
$this->db->from('entry');
$this->db->join('comments', 'entry.entry_id=comments.blog_id', 'left');
$this->db->where('entry.entry_id',$id);
$query = $this->db->get();
if($query->num_rows() != 0)
{
return $query->result_array();
}
else
{
return false;
}
}
Here is a simple dump in my view file:
Array
(
[0] => Array
(
[user_id] => 1
[entry_id] => 1
[entry_name] => twkla nnn xxx
[entry_body] => this is just UPDATED
[status] => active
[created_timestamp] => 2017-01-03 00:00:00
[updated_timestamp] => 2017-01-04 00:00:00
[id] => 1
[comment] => This is a comment
[blog_id] => 1
)
[1] => Array
(
[user_id] => 1
[entry_id] => 1
[entry_name] => twkla nnn xxx
[entry_body] => this is just UPDATED
[status] => active
[created_timestamp] => 2016-12-04 00:00:00
[updated_timestamp] => 2017-01-03 00:00:00
[id] => 2
[comment] => This is another comments
[blog_id] => 1
)
)
But, as you can see, there are MANY fields missing from the view because this is the SQL that was executed:
SELECT `entry`.`user_id` , `entry`.`entry_id` , `entry`.`entry_name` ,
`entry`.`entry_body` , `entry`.`status` , `entry`.`created_timestamp` ,
`entry`.`updated_timestamp` , `comments`.`id` , `comments`.`comment` ,
`comments`.`user_id` , `comments`.`blog_id` , `comments`.`status` ,
`comments`.`created_timestamp` , `comments`.`updated_timestamp`
FROM `entry`
LEFT JOIN `comments` ON `entry`.`entry_id` = `comments`.`blog_id`
WHERE `entry`.`entry_id` =1
Why are all the fields displaying?
You have same column names in "entry" table as well as "comments" like user_id,status and etc.. which has same column name then the main table values will be returned. Just create alias for the matching columns liek below.
comments.user_id as cuser_id, comments.status as cstatus
Replace your select statement with this.
$this->db->select('
entry.user_id as euid,
entry.entry_id,
entry.entry_name,
entry.entry_body,
entry.status as entry_status ,
entry.created_timestamp as entry_addtime,
entry.updated_timestamp as entry_updatetime,
comments.id as comments_id,
comments.comment,
comments.user_id as comments_userID,
comments.blog_id,
comments.status as comments_status,
comments.created_timestamp as comments_addtime,
comments.updated_timestamp as comments_addtime
');
Related
i have following tables
Author
id | author_name | author_detail | author_bio
books
id | author_id | book_name | book_detail
i want to display data in following way
Author Name ::
Author Detail ::
books :: 1.book1
2.book2
3.book3
4.book4
i have tried following query but didnt worked as per my requirement
select * from authors left join books on author.id=books.author_id
i have tried group concat but it gives books name with coma seperate.so i want to books detail in array
select author.author_name,author.author_detail,author.author_bio,group_concat(books.book_name) eft join books on author.id=books.author_id
i am expexting output like
Array
(
[0] => Array
(
[id] => 1
[name] => Norm
[books] => Array
(
[0] =>Array
(
[id] => 4
[book_name] => great wall
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)
[1] =>Array
(
[id] => 6
[book_name] =>new book
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)
)
)
[1] => Array
(
[id] => 2
[name] => Norm
[books] => Array
(
[0] =>Array
(
[id] => 2
[book_name] => amazing star
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)
[1] =>Array
(
[id] => 3
[book_name] =>way of journy
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)
)
)
i have checked this question also
displaying php mysql query result with one to many relationship
Can any one help me how to display data like above ?
thank you
Try this:
SELECT
A.id
A.author_name,
A.author_detail,
A.author_bio,
B.book_name,
B.created_at,
B.updated_at
FROM books AS B
LEFT JOIN author AS A
ON (A.id=B.author_id)
you will get result like this:
id | author_name | author_detail | author_bio | book_name
1 | ari | some detail | some bio | book_ari_1
1 | ari | some detail | some bio | book_ari_2
1 | ari | some detail | some bio | book_ari_3
2 | tester | some detail | some bio | book_tester_1
etc..
to make array as your expecting result you need to restructure your array result. i will asume your result array will be in $result variable
$new_result = array();
foreach ($result as $key => $value) {
if (empty($new_result[$value['id']]))
{
$new_result[$value['id']] = array(
'id' => $value['id'],
'name' => $value['name'],
'books' => array(
array(
'id' => $value['id'],
'book_name' => $value['book_name'],
'created_at' => $value['created_at'],
'updated_at' => $value['updated_at']
),
)
)
}
else
{
$new_result[$value['id']]['id'] = $value['id'];
$new_result[$value['id']]['name'] = $value['name'];
$new_result[$value['id']]['books'][] = array(
'id' => $value['id'],
'book_name' => $value['book_name'],
'created_at' => $value['created_at'],
'updated_at' => $value['updated_at']
);
}
}
the result will look like your expected. but the key number will be formated as id.
to reset key of $new_result as increment number you need to get only value use array_values() function
$new_result = array_values($new_result);
You could do it with your first query...but you'd have to check the author_id inside the record loop and show the author details only whenever the value changed (by comparing it with a value stored in a variable)...otherwise only show the book details.
So your code might (very roughly) look like this:
$query = "select whatever whatever...";
$records = $database->Execute($query);
foreach ($records as $fields) {
if ($fields['id'] != $previous_id) echo "Author ...";
echo "Book whatever whatever ...";
$previous_id = $fields['id'];
}
A more straightforward (although slightly longer) way would be to have a second query: a sub-query. And it would take place inside the loop through the results of the first (outer) query. So your outer query gets the authors and, after you show the author details, you have this separate query for books of the author...and you have a loop-within-the-outer-loop to show the details of each book.
So your code (very roughly) looks something like this:
$query = "select id, author_name, whatever from author";
$author_records = $database->Execute($query);
foreach ($author_records as $fields) {
echo "Author: {$fields['author_name']} whatever <br/>";
$subquery = "select whatever from books where id = whatever";
$book_records = $database->Execute($subquery);
foreach ($book_records as $otherfields) {
echo "Book whatever whatever";
}
}
you can do this in php no need to go in query itself but take both data in separate query i.e. books and author data
Remember i assumed $result as authors data and $result2 as books data
$item=array();
while($row=mysql_fetch_array($result))
{
$id=$row['id'];
$item[$id]['name']=$row['name'];
$item[$id]['id']=$row['id'];
$item[$id]['books']=array();
$temp=array();
while($row1=mysql_fetch_array($result2))
{
if($id==$row1['author_id'])
{
$temp['id']=$row1['id'];
$temp['book_name']=$row1['book_name'];
$temp['created_at']=$row1['created_at'];
$temp['updated_at']=$row1['updated_at'];
array_push($item['id']['books'],$temp);
}
}
}
Now here id is formatted as author's id. To get like array keys you can use array_values($item)
Is it possible to make a query that will return one time the value of the second table and set the otherones at NULL. Im stuck with this.
This is my query
return $this->db->get_results(
"
SELECT id, name, type, check_in_days, check_out_days, all_check_out_days, minimum_stay, maximum_stay, all_accom, GROUP_CONCAT( accom_id ) as accom, GROUP_CONCAT( seasons_id ) as seasons, conditional_type
FROM $this->booking_rules_table
LEFT JOIN $this->booking_rules_accom_table
ON $this->booking_rules_table.id = $this->booking_rules_accom_table.rule_id
LEFT JOIN $this->booking_rules_seasons_table
ON $this->booking_rules_table.id = $this->booking_rules_seasons_table.rule_id
GROUP BY id
"
, ARRAY_A );
This returns a array like this
[2] => Array
(
[id] => 54
[name] =>
[type] => minimum_stay
[check_in_days] => 0,1,2,3,4,5,6
[check_out_days] => 0,1,2,3,4,5,6
[all_check_out_days] => 1
[minimum_stay] => 0
[maximum_stay] => 9999
[all_accom] => 0
[accom] => 7,7,7
[seasons] => 1,3,4
[conditional_type] => compulsory
)
You see that [accom] is returning the 7 3 times because the [seasons] has 3 values.
can i fix this with my query or is there an other solution. I dont want to explode it and build the array again.
So, there's the User model, and the Item model. It's a many-to-many relation: an item can belong to many users, and a user can have many items. Therefore, there's the UserItemRel model.
To summarize:
item
id
name
date_created
date_updated
user
id
email
password
date_created
date_updated
user_item_rel
user_id
item_id
date_created
My query, before making the switch to Yii2, was this:
SELECT COUNT(UIR.`user_id`) as `favourited`, IT.`id`, IT.`name`, CA.`name` as `category`
FROM `user_item_rel` UIR
LEFT JOIN `item` IT ON UIR.`item_id` = IT.`id`
LEFT JOIN `category_item` CI ON UIR.`item_id` = CI.`item_id`
LEFT JOIN `category` CA ON CI.`category_id` = CA.`id`
WHERE UIR.`date_created` >= (SYSDATE() - INTERVAL 3 YEAR)
GROUP BY UIR.`item_id`
ORDER BY
`favourited` DESC
LIMIT 20
I've used the yii2-enhanced-gii extension to generate the models.
I want to show the 20 most favourited items in the past 48 hours, with their counts. I'm migrating from Yii1.1, and it's been quite the ride so far, and I can't figure this out.
I've found
$this->hasMany(UserItemRel::className(), ['id' => 'user_id'])
->viaTable('user_item_rel', ['id' => 'item_id'], function ($query) {
$query->andWhere(['date_created < INTERVAL 2 DAY'])
->orderBy(['COUNT(*)' => SORT_DESC]);
});
}
but how to properly use this?
The query would something like bellow. I would try to run a native query instead of trying to find out how this could be done withing the orm.
SELECT item_id, item.name, count(*) favorite
FROM user_item_rel
LEFT JOIN user ON user.id = user_item_rel.user_id
LEFT JOIN item ON item.id = user_item_rel.item_id
WHERE user_item_rel.date_created >= (sysdate() - interval 2 DAY)
GROUP BY item_id, name
ORDER BY favorite DESC
LIMIT 20
You might be able to try something like this:
$items = UserItemRel::find()
->asArray()
->select("COUNT(`user_id`) as favourited, `item_id`")
->groupBy("item_id")
->joinWith("item")
->orderBy("favourited DESC")
->indexBy("item_id")
->where("'date_created' >= '".date("Y-m-d", strtotime("-2 days"))."'")
->limit(3)
->all();
In my testing it gives me something like this:
Array
(
[1] => Array
(
[favourited] => 4
[item_id] => 1
[item] => Array
(
[id] => 1
[name] => Donec
[date_created] => 2015-08-26
[date_updated] => 2015-08-26
)
)
[8] => Array
(
[favourited] => 3
[item_id] => 8
[item] => Array
(
[id] => 8
[name] => Tellus
[date_created] => 2015-08-26
[date_updated] => 2015-08-26
)
)
[7] => Array
(
[favourited] => 2
[item_id] => 7
[item] => Array
(
[id] => 7
[name] => Mollis
[date_created] => 2015-08-26
[date_updated] => 2015-08-26
)
)
)
I have array below and I need to update database according to this.
It should be something like example code below but I don't know how to do it correctly:
UPDATE productPercent SET percent="$percent" WHERE
store="$store" AND
startDate>"$start_date" AND
endDate<"$end_date" AND
storeGroup="$storeGroup" AND
productGroup="$product_group" AND
productName LIKE '$search%'
I need to check for each store, store group, product (if contains word) and product group and then update productPercent table. Percent, product group, store group, product name and store are in different tables so some kind of inner join is needed.
I need some directions regarding this because I don't know how to start, thank you.
Array
(
[percent] => 3
[store] => Array
(
[0] => 36
[1] => 45
[2] => 56
)
[start_date] => 2015-02-09
[end_date] => 2015-03-31
[storeGroup] => Array
(
[0] => 2
[1] => 4
)
[product_group] => Array
(
[0] => 13
[1] => 31
[2] => 32
)
[search] => iphone
[setPercent] => Submit
)
UPDATED: data model - tableName: columns(connected tables)
store: id,name,startDate,endDate
storeGroup: id,storeGroupID(in table storeGroupName: id,name),storeID
productGroup: id,productID(in table productName: id,name),groupID(in table productGroupName: id,name)
productName: id,name
productPercent: id,productID,storeID,percent
$pdoHandle = $this->getPDOHandle();
$searchword = 'iphone';
$sql = "UPDATE
productPercent
inner join store on productPercent.storeID=store.id
inner join storeGroup on storeGroup.storeID=store.id
inner join productGroup on productGroup.id=storeGroup.groupID
inner join productName on productPercent.productID=productName.id and productGroup.productID=productName.id
SET percent=:percent
WHERE productName.name like :searchword";
$pdo->prepare($sql);
$pdo->setAttribute('percent', floatval($percent/100));
$pdo->setAttribute('searchword', $searchword . '%');
Im doing a search system and Im having some problems.
I need to search in two tables (news and pages), I already had sucess doing my search system for just one table, but for two tables its not easy to do.
I already use a select statment with two tables using UNION because I want to show number of search results, that is number of returned rows of my first sql statment.
But now I need to do a select statment that allows me to acess all fields of my news table and all fields of my pages table.
I need to acess in my news table this fields: id, title, content, link, date, nViews
I need to acess in my pages table this fields: id, title, content, link
Im trying to do this also with UNION, but in this case Im not having any row returning.
Do you see what I have wrong in my code?
<?php
//first I get my $search keyword
$search = $url[1];
$pdo = connecting();
//then I want to show number of returned rows for keyword searched
$readALL = $pdo->prepare("SELECT title,content FROM news WHERE title LIKE ? OR content LIKE ?
UNION SELECT title,content FROM pages WHERE title LIKE ? OR content like ?");
$readALL->bindValue(1,"%$search%", PDO::PARAM_STR);
$readALL->bindValue(2,"%$search%", PDO::PARAM_STR);
$readALL->bindValue(3,"%$search%", PDO::PARAM_STR);
$readALL->bindValue(4,"%$search%", PDO::PARAM_STR);
$readALL->execute();
//I show number of returned rows
echo '<p>Your search keyword returned <strong>'.$readALL->rowCount().'</strong> results!</p>';
//If dont return any rows I show a error message
if($readALL->rowCount() <=0){
echo 'Sorry but we didnt found any result for your keyword search.';
}
else{
//If return rows I want to show, if it is a page result I want to show title and link that I have in my page table
//if it is a news result I want to show title and link that I have in my news table and also date of news
echo '<ul class="searchlist">';
$readALL2 = $pdo->prepare("SELECT * FROM news WHERE status = ? AND title LIKE ? OR content LIKE ? LIMIT 0,4
UNION SELECT * FROM pages where title LIKE ? OR content LIKE ? LIMIT 0,4");
$readALL2->bindValue(1, '1');
$readALL2->bindValue(2, "%$search%", PDO::PARAM_STR);
$readALL2->bindValue(3, "%$search%", PDO::PARAM_STR);
$readALL2->bindValue(4, "%$search%", PDO::PARAM_STR);
$readALL2->execute();
while ($result = $readALL2->fetch(PDO::FETCH_ASSOC)){
echo '<li>';
echo '<img src="'.BASE.'/uploads/news/'.$result['thumb'].'"/>';
echo ''.$result['title'].'';
//if it is a news result I also want to show data on my list
//echo '<span id="date">'.$result['data'].'</span>';
echo '</li>';
}
echo ' </ul>';
//but how can I do my select statement to have access to my news table fields and my page table fields??
}
?>
This is my news table:
This is my pages table:
When I search on my form for keyword "doc" I get this:
Your are searching for keyword: "doc"
your search returned 2 results!
Array ( [id_news] => 472 [thumb] => 2014/07/title-of-news-11405372264.png [title] => Documents [content] => Link 1, Link 2 [ofte] => 2014-07-14 23:11:04 [views] => 0 [author] => 1 [category] => 116 [status] => 1 [id] => 1 [link] => documents ) image of news Documents
Array ( [id_news] => 473 [thumb] => 2014/07/title-of-news-21405372282.png [title] => Documents [content] => Link 1, Link 2 [ofte] => 2014-07-14 23:11:22 [views] => 0 [author] => 1 [category] => 115 [status] => 1 [id] => 1 [link] => documents ) image of news Documents
Array ( [id_news] => 472 [thumb] => 2014/07/title-of-news-11405372264.png [title] => About [content] => we are a company... [ofte] => 2014-07-14 23:11:04 [views] => 0 [author] => 1 [category] => 116 [status] => 1 [id] => 2 [link] => about ) image of news About
Array ( [id_news] => 473 [thumb] => 2014/07/title-of-news-21405372282.png [title] => About [content] => we are a company... [ofte] => 2014-07-14 23:11:22 [views] => 0 [author] => 1 [category] => 115 [status] => 1 [id] => 2 [link] => about ) image of news About
Array ( [id_news] => 472 [thumb] => 2014/07/title-of-news-11405372264.png [title] => Contacts [content] => Email: test#email.com [ofte] => 2014-07-14 23:11:04 [views] => 0 [author] => 1 [category] => 116 [status] => 1 [id] => 3 [link] => contacts ) image of news Contacts
Array ( [id_news] => 473 [thumb] => 2014/07/title-of-news-21405372282.png [title] => Contacts [content] => Email: test#email.com [ofte] => 2014-07-14 23:11:22 [views] => 0 [author] => 1 [category] => 115 [status] => 1 [id] => 3 [link] => contacts ) image of news Contacts
To query 2 tables, and have the result set contain columns from both tables:
SELECT n.id, n.status, n.views, p.id, p.title
FROM news n, pages p
WHERE n.status = ?
AND p.title = ?
...
To simplify my answer I have omitted most of your required columns, but you simply add more to the select statement. Of course, you can always use
SELECT n.*, p.*
To select all columns from both tables.
Update:
For your specific scenario, try:
SELECT n.*, p.*
FROM news n, pages p
WHERE n.title LIKE ?
OR n.content LIKE ?
OR p.title LIKE ?
OR p.content LIKE ?