Converting SQL query to codeigniter active record - php

I am working on a private message app using CodeIgniter.
I have 3 tables:
conversations
conversations_messages
conversations_members.
I am trying to join the tables by matching the conversations ids and fetch all the messages for the user who's logged in.
This is the standard sql query
SELECT
'conversations','conversation_id',
'conversations','conversation_subject',
MAX('conversations_messages','message_date') AS 'conversation_last_reply'
FROM 'conversations'
LEFT JOIN 'conversations_messages' ON 'conversations'.'conversation_id' = 'conversations_messages'.'conversation_id'
INNER JOIN 'conversations_members' ON 'conversations'.'conversation_id' = 'conversations_members'.'conversation_id'
WHERE 'conversations_members', 'user_id' = $sender_id
AND 'conversations_members','conversation_deleted' = 0
GROUP BY 'conversations'.'conversation_id'
ORDER BY 'conversation_last_reply' DESC";
Its a big query, hence; I'm not sure how to convert it to CodeIgniter active records or simply make it run with the framework.
Any corrections would be appreciated too.

Try below code with CodeIgniter active record.
$this->db->select('conversations, conversation_id, conversation_subject');
$this->db->select_max('conversations_messages.message_date', 'conversation_last_reply');
$this->db->from('conversations');
// Joining with conversations_messages table
$this->db->join('conversations_messages','conversations.id=conversations_messages.conversation_id','left');
$this->db->join('conversations_members','conversations.id= conversations_members.conversation_id','inner');
$this->db->where('conversations_members.user_id',$sender_id);
$this->db->where('conversations_members.conversation_deleted','0');
$this->db->group_by('conversations.conversation_id');
$this->db->order_by('conversation_last_reply');
// Get the results from db
$query = $this->db->get();
// Result array contains the records selected
$result_array = $query->result_array();
Happy coding
Naseem

$this->db->select('conversations, conversation_id, conversation_subject');
$this->db->select_max('conversations_messages.message_date', 'conversation_last_reply');
$this->db->from('conversations');
// Joining with conversations_messages table
$this->db->join('conversations_messages','conversations.id=conversations_messages.conversation_id','left');
$this->db->join('conversations_members','conversations.id= conversations_members.conversation_id','inner');
$this->db->where('conversations_members.user_id',$sender_id);
$this->db->where('conversations_members.conversation_deleted','0');
$this->db->group_by('conversations.conversation_id');
$this->db->order_by('conversation_last_reply');
// Get the results from db
$query = $this->db->get();
// Result array contains the records selected
$result_array = $query->result_array();

Related

Convert codeigniter query to sql query

i am little confused in wririting SQL query for joining muthiple tables.
I have perfectly write that query in codeigniter as folows
$this->db->select('*');
$this->db->from('subscription_payment');
$this->db->join('user', 'user.user_id = subscription_payment.user_id');
$this->db->join('subscription', 'subscription.subscription_id =
subscription_payment.subscription_id');
$this->db->where('subscription_payment.subscription_payment_id',$sid);
$query = $this->db->get();
$result= $query->result_array();
Help me to convert this to SQL query
Using
echo $this->db->last_query();
will produce
select * from some_table...
And this is it. Next time you can convert any query you want with easy.
select *
from subscription_payment
join user
on user.user_id = subscription_payment.user_id
join subscription
on subscription.subscription_id = subscription_payment.subscription_id
where subscription_payment.subscription_payment_id = $sid
SELECT *
FROM subscription_payment
JOIN user ON user.user_id = subscription_payment.user_id
JOIN subscription ON subscription.subscription_id = subscription_payment.subscription_id
WHERE subscription_payment.subscription_payment_id = $sid
;

The above query will not pull the information from the database

$read = "SELECT * FROM elmtree
WHERE id ='$getid' AND
INNER JOIN elmtree_users ON elmtree.userid = elmtree_users.id";
The above query will not pull the information from the database to publish to the website.
Im trying to pull the item from the database with the $getid but also join the item id with the userid who uploaded it. Then using a while loop to print out the item to screen.
Any help would be greatly appreciated.
The SQL syntax you show isn't correct. A join clause describes which tables will be available for the rest of the query; all tables you mention need to be part of the ‘FROM’ clause, so that is where the ‘JOIN’ also belongs.
SELECT *
FROM elmtree
INNER JOIN elmtree_users ON elmtree.userid = elmtree_users.id
WHERE id ='$getid'
Your SQL query was not correctly written. The AND is not used in joining tables and the WHERE statement should be after the JOIN.
Try the following:
$read = "SELECT * FROM elmtree INNER JOIN elmtree_users ON(elmtree.userid = elmtree_users.id) WHERE elmtree.id ='$getid'";
UPDATE
Could you try the following in your code (replacing $this->database with your database variable) and post the result:
if ($result = $conn->query($read)) {
while ($row = $result->fetch_assoc()) {
...
}
} else {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
$read = "SELECT * FROM elmtree INNER JOIN elmtree_users ON(elmtree.userid = elmtree_users.id) WHERE elmtree.itemid ='$getid'
Big thanks to Omari Celestine to finding the answer to the problem!

Codeigniter combining query

I want to union these 2 queries but I am getting error
Call to a member function num_rows() on array error
I am unsure of what I have done wrong. I hope someone can see if I have done the query correctly.
I have these tables:
Adults
Children
Transactions
PersonTransactions
The PersonTransactions table links up the other 3 tables via the ids
The Adults and Children table share similar fields but not entirely thats why I separated them.
Query Code Below:
$this->db->limit($limit,$start);
$this->db->select('cn.firstname AS Firstname, cn.lastname AS Lastname,t.id AS id,pt.personType AS PersonType,p.name AS ProductName,t.adults AS Adults,t.children AS Children,t.total AS Total,t.country as Country,t.transactionDate as TransactionDate');
$this->db->from('PersonTransactions AS pt');
$this->db->join('Products as p','pt.productID = p.id','LEFT');
$this->db->join('Transactions as t','pt.transactionID = t.id AND pt.personType="child"','LEFT');
$this->db->join('Children as cn','cn.id = pt.personID AND cn.personType=pt.personType','LEFT');
$query1 = $this->db->get_compiled_select();
$this->db->select('pn.firstname AS Firstname, pn.lastname AS Lastname,t.id AS id,pt.personType AS PersonType,p.name AS ProductName,t.adults AS Adults,t.children AS Children,t.total AS Total,t.country as Country,t.transactionDate as TransactionDate');
$this->db->from('PersonTransactions AS pt');
$this->db->join('Products as p','pt.productID = p.id','LEFT');
$this->db->join('Transactions as t','pt.transactionID = t.id AND pt.personType="adult"','LEFT');
$this->db->join('Person as pn','pn.id = pt.personID AND pt.personType=pt.personType','LEFT');
$query2 = $this->db->get_compiled_select();
$query = $this->db->query($query1." UNION".$query2);

two tables query, strange multiplication in the result

Hi and thanks in advance for your answer/s.
I have two tables, tracks(info on music tracks, title, lenght, cd_id..etc) and purchd_items(purchased tracks, cd_id, user_id..etc). I have this query:
function blue($id)
{
$user_id = $this->tank_auth->get_user_id();
$query = $this->db->query("SELECT tracks.id, tracks.track_id, tracks.cd_id, tracks.title, tracks.lenght, tracks.price, tracks.file, tracks.preview, tracks.hash, purchd_items.cd_id, purchd_items.name FROM tracks LEFT JOIN purchd_items ON tracks.cd_id = purchd_items.cd_id WHERE purchd_items.user_id = $user_id AND tracks.cd_id = $id GROUP BY tracks.title, purchd_items.name ORDER BY tracks.track_id");
return $query->result();
}
What I am trying to do check two tables for match and display all the info from tracks table as well as matching items from purchd_items table that will replace the entries from tracks table. If the user has already bought any tracks I want to display the download link instead of usual buy track link.Kind of like itunes, I guess.
I was sort of able to get this working using the query above but the number of items in the returned array was multiplied by the number of entries in the purchd_items table and I couldn't get rid of the duplicates.
Hope I am making sense here! Thank you!
I figured it out!
SELECT tracks.id, tracks.track_id, tracks.cd_id, tracks.title, tracks.lenght, tracks.price, tracks.file, tracks.preview, tracks.hash, purchd_items.cd_id, purchd_items.name FROM tracks LEFT JOIN purchd_items ON tracks.cd_id = purchd_items.cd_id AND purchd_items.name = tracks.title AND purchd_items.user_id = $user_id WHERE tracks.cd_id = $id ORDER BY tracks.id

Order by a SUM with multiple joins in codeigniter

Solution:
$query = $this->db->query("
SELECT *, SUM(views.times) AS sum
FROM channel
RIGHT JOIN video
ON channel.channel_id = video.channel_id
LEFT JOIN user
ON channel.user_id = user.user_id
LEFT JOIN views
ON channel.channel_id = views.channel_id
GROUP BY channel.channel_name
ORDER BY sum DESC
");
I have a query that returns a list of items.
function getfrontpage(){
$this->db->select('*');
$this->db->from('channel');
$this->db->join('video', 'channel.channel_id = video.channel_id' , 'right');
$this->db->join('user', 'channel.user_id = user.user_id');
$this->db->group_by("channel.channel_name");
$query = $this->db->get();
return $query->result();
}
Now i'm trying to order these with the SUM from another table, how can i achieve this?
Here is a picture from that table:
I want the results to be sorted by the SUM of the total of "times" for each "channel_id"
thanks in advance
I would suggest to run this through $this->db->query() instead.
It's nice to fetch simple values through CodeIgniters AR functions. But at some situations it's simply easier to build query strings instead.
In your case:
$query = $this->db->query("
SELECT channel_id, SUM(times) AS sum
FROM channel
GROUP BY channel_id
ORDER BY sum DESC
");
You can also escape most values through db->query()!
$this->db->query("
SELECT name
FROM table_name
WHERE id = ?
", array(1));
Isn't it as simple as $this->db->order_by("channel_id", "desc");? this orders the results by channel_id in descending order.
Assuming the table displayed in your question is called times_table, and has a key of user_id, channel_id, you can use the following code to join the times_table into your query so the "times" column is available to sort by.
$this->db->join("times_table", "times.user_id=channel.user_id, times.channel_id=channel.channel_id", "left");
// You've already grouped by channel_name, so grouping by channel_id is probably not necessary.
$this->db->order_by("SUM(times_table.times) DESC");
N.B. I just guessed the name of your displayed table is times_table.

Categories