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);
Related
I have 2 querys.I want to union both querys.When am trying to add both querys not getting result.
Please find below 2 querys. Even i tried to add one single core PHP Query to in codeigniter model
But not getting result. can any one please help me on this query.
Core PHP Based query in model codeigniter-method1
$sql = "select
'Amadeus' AS SupplierName,TST_Type,TKT_Type,TKTNumber,TKT_FO_REF,BasePrice,TaxPrice,Commission1,BasePrice+TaxPrice AS TotalPrice,'issued' AS tkt_type,booking_price.CreatedBy as createdby,`TicketedDate` AS created_date,CONCAT(`a3m`.`firstname`,`a3m`.`lastname`) AS created_name,a3m.account_id,`a3m`.locationvalue AS Location_ID,`a3m`.locationdescription AS Location_Name,`a3m`.costcentervalue AS CostCenter_ID,`a3m`.costcenterdescription AS CostCenter_Name
from
data_flight.booking_price
left join `a3m_account_details` `a3m` ON `a3m`.`account_id` = data_flight.booking_price.CreatedBy
where TKTNumber!=''
union all
select
'Amadeus' AS SupplierName,'' AS TST_Type,'' AS TKT_Type,br_tkt AS TKTNumber,'' AS TKT_FO_REF,br_fare_paid_B AS BasePrice, br_tax_refund_TXT AS TaxPrice,
br_cancellation_penalty AS Commission1, br_fare_total_RFT AS TotalPrice,br_cancel_type AS tkt_type,booking_refund.br_added_by AS createdby,br_refund_date AS created_date ,CONCAT(`a3m`.`firstname`,`a3m`.`lastname`) AS created_name,a3m.account_id,`a3m`.locationvalue AS Location_ID,`a3m`.locationdescription AS Location_Name,`a3m`.costcentervalue AS CostCenter_ID,`a3m`.costcenterdescription AS CostCenter_Name
from
data_flight.booking_refund
left join `a3m_account_details` `a3m` ON `a3m`.`account_id` = data_flight.booking_refund.br_added_by
where br_tkt!=''
";
echo $this->db->query($sql);
COdeigniter based query method2
$this->db->select('"Amadeus" AS SupplierName,TST_Type,TKT_Type,TKTNumber,TKT_FO_REF,BasePrice,TaxPrice,Commission1,(BasePrice+TaxPrice) AS TotalPrice,"issued" AS tkt_type,createdby,TicketedDate as created_date,CONCAT(a3m.firstname," ",a3m.lastname) AS created_name,a3m.account_id,a3m.locationvalue AS Location_ID,a3m.locationdescription AS Location_Name,a3m.costcentervalue AS CostCenter_ID,a3m.costcenterdescription AS CostCenter_Name');
$this->db->from($this->traveldb->database.".booking_price bp");
$this->db->join('a3m_account_details a3m','a3m.account_id=createdby','left');
$this->db->where('TKTNumber !=', '');
$query1 = $this->db->get();
$this->db->select('"Amadeus" AS SupplierName,"" AS TST_Type,"" AS TKT_Type,br_tkt AS TKTNumber,"" as TKT_FO_REF,br_fare_paid_B as BasePrice,br_tax_refund_TXT as TaxPrice,br_cancellation_penalty as Commission1,br_fare_total_RFT AS TotalPrice,br_cancel_type AS tkt_type,br_added_by as createdby,br_refund_date as created_date,CONCAT(a3m.firstname," ",a3m.lastname) AS created_name,a3m.account_id,a3m.locationvalue AS Location_ID,a3m.locationdescription AS Location_Name,a3m.costcentervalue AS CostCenter_ID,a3m.costcenterdescription AS CostCenter_Name');
$this->db->from($this->traveldb->database.".booking_refund bp");
$this->db->join('a3m_account_details a3m','a3m.account_id=br_added_by','left');
$this->db->where('br_tkt !=', '');
$query2 = $this->db->get();
$query = $this->db->query($query1." UNION ".$query2);
echo $this->db->last_query();
I tried both methods in my model not getting result , tried to print query it showing erros. Please help me on this.
I have the following tables:
member
id, firstName, lastName
team
id, name
teamMember
id, teamId, memberId
I am trying to access the relational table so I can output the members firstName and Lastname:
$sql = "SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId
FROM teamMember
JOIN member
JOIN team
ON teamMember.memberId = member.id
WHERE dashboardId = 1 AND team.id = 1";
I have set a hard value in the team.id so I can test to make sure it returns the members of team 1 for now.
so the end goal here is that I need to access the relational table to give me back the names of members that are associated to the team id set in the select query by ID.
I am struggling to get the output need.
And return the values like so:
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "{$row['firstName']} {$row['lastName']}<br>";
}
}
The error I am seeing is:
Notice: Trying to get property of non-object in
Which refers to: if ($result->num_rows > 0) {
The output I want to see is the members firstName and lastName from the member table
You are probably want all the results or rows associated to the desired team id. But, Using a INNER JOIN you would only get a single row for one team because that is how JOIN works.
Instead you should use a query like this :
SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId
FROM teamMember
JOIN member
ON teamMember.memberId = member.id
WHERE dashboardId = 1 AND teamMember.teamId = 1"
Hope this would work.
However, As of bool(false), your query was also broken and would not get you desired results.
In your query you have joined three tables and defined the condition for only one. This would be what your query should look like
"SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId
FROM teamMember
JOIN member
ON teamMember.memberId = member.id
JOIN team
ON teamMember.teamId= team.id
WHERE dashboardId = 1 AND team.id = 1";
I want to display all rows of table article, and for each of article row i want get the SUM of votes from another table (likes), and this with one query.
Here what i have:
$query = "SELECT article.title,article.tags,article.description,article.slug,users.username,article.photo,article.id,article.date,SUM(likes.votes) as upvotes
FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
$query .= " LEFT JOIN likes ON likes.article_id = article.id ";
But my problem with this query, i get only one row ! because in table likes there only one row ...
I want to display results based on article table (i have about 50 rows in it)... and if there nothing related to votes for a specific article, we show (0 votes).
Thank you.
Add group by to the code :
$query = "SELECT article.title, article.tags, article.description, article.slug, users.username, article.photo, article.id, article.date, SUM(likes.votes) as upvotes FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
$query .= " LEFT JOIN likes ON likes.article_id = article.id ";
$query .= " GROUP BY article.id";
Or use codeigniter method:
$this->db->select("article.title, article.tags, article.description, article.slug, users.username, article.photo, article.id, article.date");
$this->db->select("SUM(likes.votes) as upvotes", false);
$this->db->from("article");
$this->db->join("users","article.user_id = users.user_id");
$this->db->join("likes","likes.article_id = article.id");
$this->db->group_by("article.id");
$query = $this->db->get();
return $query->result_array();
A stored function is a special kind stored program that returns a single value. You use stored functions to encapsulate common formulas or business rules that are reusable among SQL statements or stored programs.
Here you query should
$query = "SELECT article.title,article.tags,article.description,article.slug,users.username,article.photo,article.id,article.date,custom_SUM(article.id) as upvotes
FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
and custom mysql function
DELIMITER $$
CREATE FUNCTION custom_SUM(p_article_id int(11)) RETURNS VARCHAR(10)
DETERMINISTIC
BEGIN
DECLARE likes varchar(10);
SET likes =(select sum(likes.votes) from likes where likes.article_id=p_article_id);
RETURN (likes);
END
refer link here http://www.mysqltutorial.org/mysql-stored-function/
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();
Hey guys need some more help
I have 3 tables USERS, PROFILEINTERESTS and INTERESTS
profile interests has the two foreign keys which link users and interests, they are just done by ID.
I have this so far
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
Now I want it so that it selects from Interests where what it gets from that query is the result.
So say that gives out 3 numbers
1
3
4
I want it to search the Interests table where ID is = to those...I just don't know how to physically write it in PHP...
Please help.
Using a JOIN:
Best option if you need values from the PROFILEINTERESTS table.
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
Using EXISTS:
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
Using IN:
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
You are on the right track, lets say you execute the query above using this PHP code:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
Then you can use a PHP loop to dynamically generate an SQL statement that will pull the desired IDs from a second table. So, for example, continuing the code above:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
I haven't tested the code, but it should work. So, this code will generate SQL like this:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
Hope that helps,
spryno724
Most likely you want to join the tables
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1