How to get all posts where author leaved a comment? - php

How to get all the posts where current user made a comment. I have a relationships between tables, but the situation is difficult to me. It should be something like this:
$posts = Yii::app()->user->comments->posts->findAll(); // don't think that is my code, it just for explanation of query chain
so I need to get all posts where user leaved a comment.
In the sql my query works fine:
SELECT tc.title, tc.content, t.post_id
FROM tbl_comment t
JOIN tbl_post tc
ON t.post_id =tc.id
WHERE author_id =43
GROUP BY t.post_id
$CD = new CDbCriteria;
$CD->condition = 'tc.author_id='.Yii::app()->user->id;
$CD->join = 'JOIN tbl_comment tc ON t.id=tc.post_id';
$posts = Post::model()->findAll($CD);
This is it.

Rather than defining your IN clause manually, you can use addInCondition(), i.e.:
$criteria=new CDbCriteria;
$criteria->addInCondition('id', $postIds)
$posts=Post::model()->findAll($criteria);
You can view the source from the Yii documentation page, and you'll see that the code there splits up the parameters and then joins them, similiar to what #Wilq is suggesting.

If you need a string for that parameter just do an implode() on your array.
Try:
$criteria->params = array(':id' => implode(',',$postIds));

Reading your code makes me think $postIds is an array of IDs. Is that right ?
If so, you can't assign $postIds to the :id query parameter, you need to do several queries whith a single posted id each time.

Related

How can I solve an problem with two select statements in one query

I want to retrieve og tags with sql in php language but I only get to see 1 result, that is the first one he reads, the other I don't get to see in page source.
this is the code with php.
$query = "SELECT metatitle FROM isacontent_content WHERE contentid = 12245
UNION ALL
SELECT name FROM isacontent_module_anchorimage WHERE contentid = 12245";
$resimage = $conn->query($query);
if(is_array($resimage)){
foreach ($resimage as $resItem){
$metaData[] = $resItem->fetch_assoc();
}
}else{
$metaData[] = $resimage->fetch_assoc();
}
$title = $metaData[0]["metatitle"];
$image = $metaData[0]["name"];
I expect that both select statements will work and I can see both contents in the meta tags
For UNION ALL, your column name must be same or you can use ALIAS for this.
but, here in your example, you can simply use INNER JOIN to get the both values from 2 tables by using 1 single query.
Example:
SELECT ic.metatitle, im.name FROM isacontent_content ic
INNER JOIN isacontent_module_anchorimage im ON im.contentid = ic.contentid
WHERE ic.contentid = 12245
Using INNER JOIN because your both tables having relation, so you can simply use INNER JOIN
Side Note:
If you know, your query will return 1 row then why are you storing data into an array here $metaData[]? you can simply store $title and $image inside you foreach() loop.
When you use union, your columns have to be in same number as it will combine results of two queries. In your case your asking for an particular content results which are stored in multiple tables, so you can go for joins.

Cross Join with php codeigniter query

Is there away to cross join from php. In example:
Currently I query a database like so:
$company_id = 20;
$templates_data = $this->db->select('template_id')
->from('dr_template_relational')
->where('dr_template_relational.company_id',$company_id)
->get()
->result_array();
What I'm looking to do is something like this:
->from('dr_template_relational')
->cross_join()
There's several responses to this question on SO but post reference a regular sql query like so:
"SELECT * FROM citys LEFT JOIN comments ON comments.city=citys.city WHERE citys.id=$id";
This would be the way to do it in SQL query but the point here is to do it in php and get the data returned with a cross join. I also realize the query can be made with in php to have it select the data and join it with code but my question is related to is there away to simply add ->cross_join() or something like that.
You can run raw query in codeigniter to solve your problem as below:
$sql 'your query here with cross join';
$query = $this->db->query($sql);
return $query->result_array();
Hope it helps you :)
You can use CI join method.
$company_id = 20;
$templates_data = $this->db->select('dr_template_relational.template_id')
->where('dr_template_relational.company_id',$company_id)
->join('table','dr_template_relational.company_id=table.company_id','LEFT')
->get()
->result_array();
where 'LEFT' is the join type

Only one query instead of two

I have 2 tables, one is called post and one is called followers. Both tables have one row that is called userID. I want to show only posts from people that the person follows. I tried to use one MySQL query for that but it was not working at all.
Right now, I'm using a workaround like this:
$getFollowing = mysqli_query($db, "SELECT * FROM followers WHERE userID = '$myuserID'");
while($row = mysqli_fetch_object($getFollowing))
{
$FollowingArray[] = $row->followsID;
}
if (is_null($FollowingArray)) {
// not following someone
}
else {
$following = implode(',', $FollowingArray);
}
$getPosts = mysqli_query($db, "SELECT * FROM posts WHERE userID IN($following) ORDER BY postDate DESC");
As you might imagine im trying to make only one call to the database. So instead of making a call to receive $following as an array, I want to put it all in one query. Is that possible?
Use an SQL JOIN query to accomplish this.
Assuming $myuserID is an supposed to be an integer, we can escape it simply by casting it to an integer to avoid SQL-injection.
Try reading this wikipedia article and make sure you understand it. SQL-injections can be used to delete databases, for example, and a lot of other nasty stuff.
Something like this:
PHP code:
$escapedmyuserID = (int)$myuserID; // make sure we don't get any nasty SQL-injections
and then, the sql query:
SELECT *
FROM followers
LEFT JOIN posts ON followers.someColumn = posts.someColumn
WHERE followers.userID = '$escapedmyuserID'
ORDER BY posts.postDate DESC

Avoiding a query inside a loop in my situation

I have quite a complicated situation here. I can't find a better way to solve this without putting a SELECT query inside a loop that rolls over 70000 times when I enter that page (don't worry, I use array_chunk to split the array into pages). I guess this would be a resource killer if I use a query here. Because of this, here I am, asking a question.
I have this big array I need to loop on:
$images = scandir($imgit_root_path . '/' . IMAGES_PATH);
$indexhtm = array_search('index.htm', $images);
unset($images[0], $images[1], $images[$indexhtm]);
Now I have an array with all file names of the files (images) in my IMAGES_PATH. Now the problem comes here:
Some of these images are registered on the database, because registered users have their images listed on my database. Now I need to retrieve the user_id based on the image name that the array above gives me.
Inside a loop I simply did this:
foreach ($images as $image_name)
{
$query = $db->prepare('SELECT user_id FROM imgit_images WHERE image_name = :name');
$query->bindValue(':name', $image_name, PDO::PARAM_STR);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$user_id = $row['user_id'];
echo $user_id;
}
This works just fine, but the efficiency equals to 0. Using that user_id I plan on getting other stuff from the imgit_users table, such as username, which would require another query inside that loop.
This is too much and I need a simpler way to deal with this.
Is there a way to get those user_ids before going inside the loop and use them IN the loop?
This is the table structure from imgit_images:
While this is the schema for imgit_users:
Something like this would work (I'm not sure if it's possible to prepare the WHERE IN query since the # of values is unknown... Else, make sure you sanatize $images):
$image_names = "'".implode("', '", $images)."'";
$query = $db->prepare("SELECT img.user_id, image_name, username
FROM imgit_images img
INNER JOIN imgit_users u ON u.user_id = img.user_id
WHERE image_name IN(".$image_names.")");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo $row['user_id']."'s image is ".$row['image_name'];
}
You might need to tweak it a little (haven't tested it), but you seem to be able to, so I'm not worried!
Not sure if it is going to help, but I see a couple of optimizations that may be possible:
Prepare the query outside the loop, and rebound/execute/get result within the loop. If query preparation is expensive, you may be saving quite a bit of time.
You can pass an array as in Passing an array to a query using a WHERE clause and obtain the image and user id, that way you may be able to fragment your query into a smaller number of queries.
Can you not just use an INNER JOIN in your query, this way each iteration of the loop will return details of the corresponding user with it. Change your query to something like (i'm making assumptions as to the structure of your tables here):
SELECT imgit_users.user_id
,imgit_users.username
,imgit_users.other_column_and_so_on
FROM imgit_images
INNER JOIN imgit_users ON imgit_users.user_id = imgit_images.user_id
WHERE imgit_images.image_name = :name
This obviously doesn't avoid the need for a loop (you could probably use string concatenation to build up the IN part of your where clause, but you'd probably use a join here anyway) but it would return the user's information on each iteration and prevent the need for further iterations to get the user's info.
PDO makes writing your query securely a cinch.
$placeholders = implode(',', array_fill(0, count($images), '?'));
$sql = "SELECT u.username
FROM imgit_images i
INNER JOIN imgit_users u ON i.user_id = u.id
WHERE i.image_name IN ({$placeholders})";
$stmt = $db->prepare($sql);
$stmt->execute($images);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// use $row['username']
}
Create a string of comma separated ?s and write them into IN's parentheses. Then pass the array of images to execute(). Easily done, and now all of your desired data is available in a single resultset from a single query. (Add additional columns to your query's SELECT clause as needed.)

Showing data from 2 models in a grid with Yii

I'm trying to select data from two tables and show that data in a paginated grid view. The problem is that Yii is joining the data with a SQL join (because I told it to do it) and because of that it's not showing the correct number of items per page.
To make in clear, I'm selecting from topics and messages_in_topics, and I'm joining then with
$criteria->together = true;
This makes MySQL to return a row for each message (and the related topics). Example:
id_topic topic id_messages message
1 topic1 1 message1_in_topic1
1 topic1 2 message2_in_topic1
1 topic1 3 message3_in_topic1
2 topic2 4 message1_in_topic2
2 topic2 5 message2_in_topic2
There are only 2 topics, but Yii's paginator thinks there are 5.
The fastest way to "fix" this is grouping by the id_topic field, anyways, I can't do that because there's a where condition which searches with the like statement.
Thank you
EDIT:
Here's my action code:
$criteria = new CDbCriteria;
$get_s = Yii::app()->request->getQuery('s', '');
if( $get_s ){
$criteria->compare("topic_title", $get_s, true);
$criteria->compare("message_text", $get_s, true, 'OR');
}
$criteria->with = array('messages');
$criteria->addCondition(array( ...... )); <--- some rules like if the topic is validated...
$dataProvider = new CActiveDataProvider('Topics', array(
'criteria'=>$criteria,
'pagination=>array('pageSize'=>15)
));
Actually, what happens there is that the information being displayed is in regard to your messages. The repeated topic values are because these topics are the corresponding related data to the message.
You could try to tell your query to use GROUP BY in the results...
SELECT t.id_topic, t.topic, COUNT(m.id_messages)
FROM topics t LEFT JOIN messages m ON t.id_topic = m.id_topic
GROUP BY t.id_topic
This way, more or less, you can display the count of messages-per-topic.
I could help you more if you'd show us your SQL.
EDIT: After seeing your code, here is my guess:
$criteria = new CDbCriteria;
$get_s = Yii::app()->request->getQuery('s', '');
if( $get_s ){
$criteria->compare("topic_title", $get_s, true);
$criteria->compare("message_text", $get_s, true, 'OR');
}
$criteria->with = array('messages');
$criteria->addCondition(array( ...... )); <--- some rules like if the topic is validated...
$dataProvider = new CActiveDataProvider('Topics', array(
'criteria'=>$criteria,
'pagination=>array('pageSize'=>15)
));
You can make sure the query isn't complicated by yii's formatting by pouring it using only three basic properties of CDbCriteria:
$criteria->select is exactly the list of columns you want to select.
$criteria->condition is exactly the WHERE condition, I honestly prefer using a string to an array, since using the string allows me to use the exact condition I put in here.
$criteria->join is attached immediately after the $model->tableName() you specify in the CActiveDataProvider constructor.
$criteria->group is added at the end of the query, you just need to specify the grouping column.
Also, You can also make sure to set these properties directly, so you actually descompose your query into the CDbCriteria object. For instance:
SELECT t.id_topic, t.topic, COUNT(m.id_messages)
FROM topics t LEFT JOIN messages m ON t.id_topic = m.id_topic
GROUP BY t.id_topic
would be like this
/*1*/ $criteria->select = 't.id_topic, t.topic, COUNT(m.id_messages)';
/*2*/ $criteria->condition = 't.topic_title LIKE %'.$get_s.'% OR ...';/* add your conditions here*/
/*3*/ $criteria->join = 'LEFT JOIN messages m ON t.id_topic = m.id_topic'; //Full join statement here, including the nature of the join.
/*4*/ $criteria->group = 't.id_topic';
IMPORTANT: take into account that since you pass your Topics classname to the CActiveDataProvider constructor, the table under Topics will be known as t. Any other tables must be specified as well (Pretty much like messages m or messages AS m)in the join condition otherwise you might get a column xxxx is ambiguous warning.
Don't pass out the chance of giving an eye to CDbCriteria and CActiveDataProvider for any questions you might have.
The problem isn't the paginator, it is you query. If you run the query:
SELECT *
FROM topics as t
INNER JOIN messages_in_topics as mt
ON mt.topics_id = t.id
INNER JOIN messages as m
ON m.id = mt.messages_id
You will get 5 results, as show in your example above.
So more importantly, what are you trying to do?
Also, your table shows a MANY_MANY relationship (message1 has 2 topics, topic1 has 3 messages), is your database set up the right way, and are your model relations configured accordingly?
Are you trying to show ALL messages in each topic on a single line?
Are you trying to show ALL topics and list each message with that topic?
Assuming you have relations set up correctly, you can just use: $messages=$topics->messages; and get an array with all the messages listed.
Conversely, you can do $topics=$messages->topics; to get the topics.

Categories