Get total comments of article in PHP with NotORM - php

My table ofcomments looks like:
| ID | article_id | user_id | ...
|-------------------------------|
| 1 | 1 | 1 | ...
| 2 | 2 | 2 | ...
| 3 | 2 | 1 | ...
| 4 | 3 | 2 | ...
AndI need to get top 5 articles with the most comments. When I use this statement in SQL console SELECT 'article_id', count(*) as 'total' FROM 'comments' GROUP BY 'article_id' ORDER BY 'total' LIMIT 5, then I get everything I want. But I need to do this with NotORM and this is where I stucked at. This is my function to get these articles:
function getBestActive() {
$items = $this->db->comments()
->select("article_id, count(*) as 'total'")
->order("total DESC")
->limit(5);
$articles = array();
foreach($items as $item) {
$article = $this->db->article('id', $item['article_id'])->fetch();
$article['img'] = "thumb/{$article['uri']}.jpg";
$article['comments'] = $item['total'];
$articles[] = $article;
}
return $articles;
}
But it returns me array with only 1 article (the most commented) and I need the most 5 articles. Or is it possible to execute custom SQL statement with NotORM (that could be answer too)?

Oh now I see. I forget to add group() function. So using this selection everything works:
$items = $this->db->comments()
->select("article_id, count(*) as 'total'")
->group("article_id")
->order("total DESC")
->limit(5);

Related

How to query based on multiple relations between columns - MySQL?

I have four columns in a properties table: property_id, value, id, material_id.
I also have an array of properties: Array $properties
The schema is a bit complicated, because I want to find the material_id based on the matching properties.
An example:
$properties = array(['property_id'=>1,'value'=>3],['property_id'=>2,'value'=>6],['property_id'=>3,'value'=>4]);
Example table output:
+----+-------------+-------------+-------+
| id | material_id | property_id | value |
+----+-------------+-------------+-------+
| 1 | 1 | 3 | 5 |
| 2 | 1 | 3 | 5 |
| 3 | 1 | 3 | 5 |
| 4 | 2 | 1 | 3 |
| 5 | 2 | 2 | 6 |
| 6 | 2 | 3 | 4 |
| 10 | 4 | 1 | 9 |
| 11 | 4 | 2 | 3 |
| 12 | 4 | 3 | 6 |
+----+-------------+-------------+-------+
Now, I need material_id that satisfies all the properties. How can I do that..? Do I need to use exist statement of MySQL?
Now, for each element in your array you will want to run a statement that looks like this:
SELECT material_id FROM properties WHERE property_id = 2 AND value = 3;
Do you need help on the php code also? You could run a for each loop, but I will need to know what way you are using to communicate with your database for more specifics.
edit
foreach ($properties as $foo => $bar)
{
$sql = 'SELECT material_id FROM properties WHERE ';
foreach ($bar as $key => $value)
{
$sql .= $key .' = '. $value .' AND ';
}
$sql .= 'true';
*run your PDO code on $sql here*
}
On behalf of performance, it's not a good idea to run a query per array's value. If you have an oversized array things can get pretty slower.
So, best solution can be to build a single query including all conditions presented on $properties array:
<?php
$properties = array(['property_id'=>1,'value'=>3],['property_id'=>2,'value'=>6],['property_id'=>3,'value'=>4]);
$qCondition = [];
foreach($properties as $prop) {
$q = sprintf("(property_id = %d AND value = %d)", $prop["property_id"], $prop["value"]);
$qCondition[] = $q;
}
// assuming that your database table name is 'materials'
$sql = sprintf("SELECT * FROM materials WHERE (" . implode(" OR ", $qCondition) . ")");
echo $sql;
Result:
SELECT * FROM materials
WHERE ((property_id = 1 AND value = 3) OR (property_id = 2 AND value = 6) OR (property_id = 3 AND value = 4))
Therefore, you need to run only one single query to get all desired rows.
You can play with suggested solution here: http://ideone.com/kaE4sw

Zend Framework 1. Fetch comments

I can't create an appropriate query which could select all comments connected with one particular image and get those comments authors.
I would like to create a query something like:
select a comment where comment_id == image_id && user_id(table comments) == user_id(table users)
This is MySQL part:
Table 'comments'
id | comment | user_id | image_id |
1 | test 1 | 1 | 1 |
2 | test 2 | 1 | 2 |
3 | test 3 | 2 | 1 |
Table 'users'
id | name |
1 | test1 |
2 | test2 |
Table 'images'
id | img |
1 | test.jpg |
2 | test.jpg |
3 | test.jpg |
4 | test.jpg |
Controller Part:
$imageId = $filter->filter ($request->getParam('id'));
$this->view->imageId = $filter->filter ($request->getParam('id'));
$this->view->imageChosen = $images->fetchRow($images->select()->where('id = ?', $imageId));
$users = new Users();
$userChosen = new Users();
$comments = new Comments();
$this->view->comments = $comments->fetchAll();
$this->view->userChosen = $users->fetchRow($users->select()->where('id = ?', $this->view->imageChosen->author_id));
$this->view->commentsChosen = $comments->fetchAll($comments->select()->where('id = ?', $imageId));
View part:
for ($i=0; $i < count($this->commentsChosen); $i++) {
echo $this->commentChosen[$i]->comment;
}
Right now I only get the very first comment.
What I mean is I need all comments belonging to each picture as well as authors info.
Thanks for your help!
As you've said, you can fetch the image info with your query, I'll extend it in order to fetch the user info too:
$select = $comments->select()->setIntegrityCheck(false)
->from('comments')
->joinInner('users', 'users.id = comments.user_id')
->where('comments.image_id = ?', $this->view->imageChosen->id);
$this->view->commentsChosen = $comments->fetchAll($select);
The generated query would be:
SELECT comments.* users.* FROM comments
INNER JOIN users ON users.id = comments.user_id
WHERE comments.image_id = [Your_id_here]
I hope this helps!
I've managed to get all comments belonging to each picture.
Controller:
$this->view->commentsChosen = $comments->fetchAll($comments->select()->where('image_id = ?', $this->view->imageChosen->id));
View:
for ($i=0; $i<count($this->commentsChosen); $i++) {
echo $this->commentsChosen[$i]->comment;
//Have 'user_id' only
echo $this->commentsChosen[$i]->user_id;
}
However, I still can't get authors details.

Yii criteria selecting all rows

I am useing Yii framework to do a criteria selection for all rows that fit the criteria.
I am trying to take the ID of one table and search another tables codes that contain the prefix of the ID. (exp ID-code or 1-sdfa). Currently the code below is returning all of the rows as a result. Below are the details, any insight would help. Thank you.
[table 1]
tbl_School
---------------------------
| ID | Name |
---------------------------
| 1 | forist hills |
| 2 | Dhs |
---------------------------
[table 2]
tbl_ticket
------------------
| ID | code |
------------------
| 1 | 1-fd23s |
| 2 | 2-fdet2 |
| 3 | 1-4wscd |
| 4 | 2-oifjd |
| 5 | 1-zzds6 |
------------------
After runing the function on ID=1 I would like to see
------------------
| ID | code |
------------------
| 1 | 1-fd23s |
| 3 | 1-4wscd |
| 5 | 1-zzds6 |
------------------
Here is my code:
public static function get_tickets($ticket_ID){
$match = '';
$match = addcslashes($match, "$ticket_ID".'_%');
$q = new CDbCriteria( array(
'condition' => "code LIKE :match",
'params' => array(':match' => "$match%")
) );
$rows = Ticket::model()->findAll( $q );
return $rows;
}
PDO does escaping for you so you don't need to do the addcslashes yourself (I didn't even know that existed, always used addslashes :) )
Secondly, you end up selecting on [NUMBER]_%%, those are 3 wildcards.
As Ryan already changed in its comment, you might want to select on -% instead:
public static function get_tickets($ticket_ID){
$ticket_ID = intval($ticket_ID);
if (!$ticket_ID)
return null;
$q = new CDbCriteria( array(
'condition' => "code LIKE :match",
'params' => array(':match' => $ticket_ID . "-%")
) );
$rows = Ticket::model()->findAll( $q );
return $rows;
}
As you can see, I did do a numeric sanity check for the ticket number, just like being cautious.
Lastly: I hope you don't mind the suggestion, but isn't it simply possible adding the ticket number as a separate column? You are going to end up with perfectly avoidable performance problems if there are a lot of rows in this table. With a separate column that is an index you'd use a lot less cpu for the same result.

Table join: unable to show the data what I want

If I have table like this:
ID | Title | Topic | Summary
1 | A | Technology | ...
2 | B | Health | ...
3 | C | Sport | ...
This is my CI_Model:
function show($limit, $offset)
{
$this->db->select('document.id, document.title, document.summary, document.id_topic AS topic');
$this->db->from('document');
$this->db->join('topic', 'topic.id_topic = document.id_topic');
$this->db->limit($limit, $offset);
$this->db->order_by('id', 'asc');
return $this->db->get()->result();
}
This is my Controller:
$docdata = $this->Trainingmodel->show($this->limit, $offset);
...
$this->table->set_heading('ID', 'Title', 'Topic', 'Summary');
foreach ($docdata as $doc)
{
$this->table->add_row($doc->id, $doc->title, $doc->topic, $doc->summary);
}
Evidently the topic shows it's id, not name.
For example:
ID | Title | Topic | Summary
1 | A | 1 | ...
2 | B | 2 | ...
3 | C | 3 | ...
What should I do? I want to show topic's name, not topic's id.
Looking at your table structure you posted as comments in the other answers, I think you need topic.topic in your select() and topic.id = document.id_topic in your join() -
$this->db->select('document.id, document.title, document.summary, topic.topic');
$this->db->from('document');
$this->db->join('topic', 'topic.id = document.id_topic');
$this->db->select('document.id, document.title, document.summary, topic.topic');
$this->db->from('document');
$this->db->join('topic', 'topic.id = document.id_topic');
Maybe its because of this document.id_topic
$this->db->select('document.id, document.title, document.summary, document.id_topic AS topic');
should it be something like document.topic or document.name_topic ?

Trouble structuring MySQL query with one-to-many over multiple tables

I have a blog-style app that allows users to tag each post with topics. I keep this data in three separate tables: posts (for the actual blog posts), topics (for the various tags), and posts_topics (a table that stores the relationships between the two).
In order to keep the MVC structure (I'm using Codeigniter) as clean as possible, I'd like to run one MySQL query that grabs all the post data and associated topic data and returns it in one array or object. So far, I'm not having any luck.
The table structure is like this:
Posts
+--------+---------------+------------+-----------+--------------+---------------+
|post_id | post_user_id | post_title | post_body | post_created | post_modified |
+--------+---------------+------------+-----------+--------------+---------------+
| 1 | 1 | Post 1 | Body 1 | 00-00-00 | 00-00-00 |
| 2 | 1 | Post 1 | Body 1 | 00-00-00 | 00-00-00 |
+--------+---------------+------------+-----------+--------------+---------------+
// this table governs relationships between posts and topics
Posts_topics
+--------------+---------------------+-------------------------+-----------------+
|post_topic_id | post_topic_post_id | post_topic_topic_id | post_topic_created |
+--------------+---------------------+-------------------------+-----------------+
| 1 | 1 | 1 | 00-00-00 |
| 2 | 1 | 2 | 00-00-00 |
| 3 | 2 | 2 | 00-00-00 |
| 4 | 2 | 3 | 00-00-00 |
+--------------+---------------------+-------------------------+-----------------+
Topics
+---------+-------------+-----------+----------------+
|topic_id | topic_name | topic_num | topic_modified |
+---------+-------------+-----------+----------------+
| 1 | Politics | 1 | 00-00-00 |
| 2 | Religion | 2 | 00-00-00 |
| 3 | Sports | 1 | 00-00-00 |
+---------+-------------+-----------+----------------+
I have tried this simple query with n success:
select * from posts as p inner join posts_topics as pt on pt.post_topic_post_id = post_id join topics as t on t.topic_id = pt.post_topic_topic id
I've also tried using GROUP_CONCAT, but that gives me two problems: 1) I need all the fields from Topics, not just the names, and 2) I have a glitch in my MySQL so all GROUP_CONCAT data is returned as a BLOB (see here).
I'm also open to hearing any suggestions where I run two queries and try to build out an array for each result; I tried that with the code below but failed (this code also includes joining the user table, which would be great to keep that as well):
$this->db->select('u.username,u.id,s.*');
$this->db->from('posts as p');
$this->db->join('users as u', 'u.id = s.post_user_id');
$this->db->order_by('post_modified', 'desc');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$posts = $query->result_array();
foreach($posts as $p)
{
$this->db->from('posts_topics as p');
$this->db->join('topics as t','t.topic_id = p.post_topic_topic_id');
$this->db->where('p.post_topic_post_id',$p['post_id']);
$this->db->order_by('t.topic_name','asc');
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach($query->result_array() as $t)
{
$p['topics'][$t['topic_name']] = $t;
}
}
}
return $posts;
}
Any help greatly appreciated.
This query should do the trick. Just change the * to the field list you desire so you are not pulling excess data every time you run the query.
Select
*
FROM
posts,
post_topics,
topics
WHERE
post_topic_topic_id = topic_id AND
post_topic_post_id = post_id
ORDER BY
post_id, topic_id;
Select
*
FROM
posts,
post_topics,
topics,
users
WHERE
post_topic_topic_id = topic_id AND
post_topic_post_id = post_id AND
post_user_id = user_id
ORDER BY
post_id, topic_id;
Holy Cow, You Can do it! See it helps to help. Never knew, try this
Select
post_id,
GROUP_CONCAT(DISTINCT topic_name) as names
FROM
posts,
post_topics,
topics
WHERE
post_topic_topic_id = topic_id AND
post_topic_post_id = post_id
GROUP BY
post_id;
You get
1, 'politics,relligion'
2, 'sports,relligion'

Categories