insert php code in sql query - php

function search_num_rows($param){
$company_name=$param['company_name'];
$loan_no=$param['loan_no'];
$q = $this->db->query("select Count(0) as num_rows
from contact_new
inner join companies c on contact_new.company_id = c.id
inner join history on contact_new.id = history.receiver_email
inner join escalation_level on contact_new.escalation_level_id = escalation_level.id
inner join departments on contact_new.departmend_id = departments.id
WHERE loan_no= '$loan_no' if($company_name){ AND company_name= '$company_name'} ")->result();
return $q[0]->num_rows;
}
can i insert the php code as i done in where clause.Is there any other way to do this without using active records.

It's actually very easy:
function search_num_rows($param){
$company_name = (isset($param['company_name']) && !empty($param['company_name']) ? " AND company_name = '$param[company_name]'" : '');
$loan_no=$param['loan_no'];
$q = $this->db->query("select Count(0) as num_rows
from contact_new
inner join companies c on contact_new.company_id = c.id
inner join history on contact_new.id = history.receiver_email
inner join escalation_level on contact_new.escalation_level_id = escalation_level.id
inner join departments on contact_new.departmend_id = departments.id
WHERE loan_no= '$loan_no' $company_name")->result();
return $q[0]->num_rows;
}

Related

php mysql use subquery result in WHERE clause in the same query

is it possible to use a subquery result as a criteria in WHERE clause in the same query. i have this sql code. i want to compare the ASSESSEDINCLASS which is a result in the subquery and C.SLOTS to determine it the slot is full or not. is this even possible in a single query? thanks in advance
$str = "SELECT
c.id,
c.code AS classcode,
section.name AS sectionname,
subject.code,
subject.subdesc,
c.units,
sched.name AS schedule,
c.slots,
c.dissolved,
c.tutorial,
c.inst,
instructor.lname,
instructor.fname,
instructor.mname,
instructor.suffix,
(SELECT
Count(e.enrollno)
FROM
enrolldet AS e
Inner Join enroll ON e.enrollno = enroll.enrollno
Inner Join class ON e.class = class.id
WHERE
enroll.validated = '1' AND
class.id = c.id) as validatedinclass,
(SELECT
Count(e.enrollno)
FROM
enrolldet AS e
Inner Join enroll ON e.enrollno = enroll.enrollno
Inner Join class ON e.class = class.id
WHERE
enroll.assessed = '1' AND
class.id = c.id) as assessedinclass,
(SELECT
q.id
FROM
merged
Inner Join class AS q ON merged.mothercode = q.id
WHERE
merged.mergefrom = c.id) AS mergedto_mothercode
FROM
class AS c
Left Join sched ON c.sched = sched.id
Left Join section ON c.section = section.id
Left Join subject ON c.subject = subject.id
Left Join instructor ON c.inst = instructor.userid
Left Join course ON section.course = course.id
Inner Join period ON c.period = period.id
WHERE
(period.id = '".$period."' OR period.code = '".$period."')";
if($status == 'open'){
$str .= " AND c.slots < assessedinclass";
}
$str .= " ORDER BY subject.subdesc";
To answer your question yes you could by using Having clause, Make you use it after where clause
having assessedinclass = someval
Or
$str .= " HAVING c.slots < assessedinclass";
But what i prefer don't use dependent sub queries instead use join for these as sub clause to your main query somewhat like below
SELECT ....,
COALESCE(aic.assessedinclass, 0) AS assessedinclass,
FROM class AS c
JOINS....
LEFT JOIN (SELECT class.id,
COUNT(e.enrollno) AS assessedinclass
FROM enrolldet AS e
INNER JOIN enroll
ON e.enrollno = enroll.enrollno
INNER JOIN class
ON e.class = class.id
WHERE enroll.assessed = '1'
GROUP BY class.id) aic
ON aic.id = c.id
WHERE ( period.id = '".$period."' OR period.code = '".$period."' )
AND c.slots < COALESCE(aic.assessedinclass, 0)

how to update multiple (5) tables using left join?

I always use left join in drop select and I dont know yet how to use it on update.
I've search a lot but I see only two tables. Im confuse when applying it in three or more table update.
Please check my query:
public function updateUser($edit_id,$username)
{
$stmt=$this->conn->prepare("UPDATE tbl_login LEFT JOIN activity_logs ON tbl_login.username = activity_logs.activity_logs,
LEFT JOIN tbl_files ON tbl_login.username = tbl_files.file_uploader,
LEFT JOIN tbl_manfiles ON tbl_login.username = tbl_manfiles.file_uploader,
LEFT JOIN tbl_section ON tbl_login.username = tbl_section.creator,
LEFT JOIN tbl_adfiles ON tbl_login.username = tbl_adfiles.adfile_uploader
SET tbl_login.username=:username
WHERE id=:id");
$stmt->execute(array(":id"=>$edit_id, ":username"=>$username));
return $stmt;
}
$query = "UPDATE profiledata t1 JOIN profileprivacy t2 ON (t1.uid = t2.uid)
SET t1.aboutyou = '$aboutyou', t1.quotes = '$quotes',
t2.aboutyouPrivacy = '$aboutyouPrivacy', t2.quotesPrivacy = '$quotesPrivacy'
WHERE t1.uid = '$sess_uid'";
update two tables at once

MYSQL Query to Codeigniter Query

I have the query below that works fine when I use it in phpMyAdmin, I am just a bit unsure how to do it within the CI framework when I have the m.id etc in place.
Query:
SELECT DISTINCT m.name, m.id, c.id, c.name
FROM `default_ps_products` p
INNER JOIN `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
INNER JOIN `default_ps_product_x_cats` x ON p.id = x.product_id
INNER JOIN `default_ps_products_categories` c ON x.category_id = c.id
There are many ways.
Example 1:
$result = $this->db
->select('m.name, m.id, c.id, c.name')
->distinct()
->join('default_ps_products_manufacturers m', 'p.manufacturer_id=m.id')
->join('default_ps_product_x_cats x', 'p.id=x.product_id')
->join('default_ps_products_categories c', 'x.category_id=c.id')
->get('default_ps_products p')
->result();
echo $this->db->last_query();
Sometimes the active record can't produce the query you want. So you can write it yourself.
Example 2:
$query = "SELECT DISTINCT m.name, m.id, c.id, c.name
FROM `default_ps_products` p
INNER JOIN `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
INNER JOIN `default_ps_product_x_cats` x ON p.id = x.product_id
INNER JOIN `default_ps_products_categories` c ON x.category_id = c.id";
$result = $this->db
->query($query)
->result();
echo $this->db->last_query();
In this second example, db::query() can take an array as the second parameter that will replace any question marks (?) within $query with the respective value. For example say you needed to add some where values to your query.
Example 3:
$query = "SELECT DISTINCT m.name, m.id, c.id, c.name
FROM `default_ps_products` p
INNER JOIN `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
INNER JOIN `default_ps_product_x_cats` x ON p.id = x.product_id
INNER JOIN `default_ps_products_categories` c ON x.category_id = c.id
WHERE c.id=?";
$result = $this->db
->query($query, array(1))
->result();
echo $this->db->last_query();

Extracting single data using limit with 5 tables involve

so i have 5 tables in which it is interconnected with foreign keys
and here is a sample output of table 3
what i wanted to do in table number 3 is to extract the SubdeptID of user with userid of 10 but in this case it has 2 userid10 so its print both. what i want to print is only the one with latter TransferID. my select statement is this
$sql_exp = "SELECT a.UserID, b.Employeename, c.TransferID, e.Department
FROM dbo.FA_Laptop a
INNER JOIN dbo.users b
on a.UserID = b.UserID
INNER JOIN dbo.SubDeptTransfer c
ON a.UserID = c.UserID
INNER JOIN dbo.SubDept d
ON c.SudDeptID = d.SubDeptID
INNER JOIN dbo.departments e
ON d.DeptID = e.DeptID
WHERE a.FAID = '$faidf' ORDER by c.TransferID DESC LIMIT 1";
my php code is
$rs = $conn->Execute($sql_exp);
if ($rs->EOF) {
echo "<tr><td>Please check for the Employee Name or the Department</td>";
} else {
while (!$rs->EOF){
echo "<tr><td>".$rs->Fields("Department")." / ".$rs->Fields("EmployeeName")."</td>";
$rs->movenext();
}
$rs->Close();
}
im having an error in "LIMIT" query.
MSSQL don't have LIMIT keyword.
Use TOP instead LIMIT.
$sql_exp = "SELECT TOP 1 a.UserID, b.Employeename, c.TransferID, e.Department
FROM dbo.FA_Laptop a
INNER JOIN dbo.users b
on a.UserID = b.UserID
INNER JOIN dbo.SubDeptTransfer c
ON a.UserID = c.UserID
INNER JOIN dbo.SubDept d
ON c.SudDeptID = d.SubDeptID
INNER JOIN dbo.departments e
ON d.DeptID = e.DeptID
WHERE a.FAID = '$faidf' ORDER by c.TransferID DESC";

Displaying results from multiple tables SQL/PHP

I currently have a database with 12 tables. I am doing a php query to pull the information from the database but I am not getting anything displayed. The query alone bridges all the tables starting with table schedule that have a foreign key related. Should I need to start the query from the table class and bridge with other tables?
TABLE DESIGN- PICTURE
If you like to duplicate my design- QUERY
$query = ("SELECT class_name, class_caption, class_credit_hours, class_description
FROM schedule
INNER JOIN section
ON class.id = section.class_id
INNER JOIN faculty
ON faculty.id = section.faculty_id
INNER JOIN faculty
ON faculty.id = office_hours.faculty_id
INNER JOIN faculty_titles
ON faculty_titles.faculty_id = faculty.id
INNER JOIN faculty_education
ON faculty_education.faculty_id = faculty.id
INNER JOIN section
ON section.faculty_id = faculty.id
INNER JOIN class
ON class.id = section.class_id
INNER JOIN major_class_br
ON major_class_br.class_id = class.id
INNER JOIN major_minor
ON major_class_br.major_minor_id = major_minor.id
");
//execute query
$result = mysql_query($query);
if ($result){
$totalhours = 0;
while ($row = mysql_fetch_assoc( $result ))
{
print "<b>" . $row['class_name'] . "</b><br>";
print $row['class_caption'] . "<br>";
print $row['class_description'] . "<br>";
print $row ['class_credit_hours'] . "hrs. <br>";
print "------------------------------<br />";
$totalhours += $row['class_credit_hours'];
}
}
SQL fiddle query
SELECT class_name, class_caption, class_credit_hours, class_description
FROM schedule
INNER JOIN section
ON class.id = section.class_id
Right here there's a problem: you are doing a INNER JOIN using the field 'class.id' but the table 'class' isn't in either side of the JOIN. So it won't work.
The query should start like this:
SELECT class_name, class_caption, class_credit_hours, class_description
FROM class
INNER JOIN section
ON class.id = section.class_id
And then do the JOIN with the table 'schedule' with the table it shares a common index (I guess it would be class).
The complete query should be something like this:
SELECT class.class_name, class.class_caption, class.class_credit_hours, class.class_description
FROM class
INNER JOIN section
ON class.id = section.class_id
INNER JOIN faculty
ON faculty.id = section.faculty_id OR faculty.id = office_hours.faculty_id
INNER JOIN faculty_titles
ON faculty_titles.faculty_id = faculty.id
INNER JOIN faculty_education
ON faculty_education.faculty_id = faculty.id
INNER JOIN major_class_br
ON major_class_br.class_id = class.id
INNER JOIN major_minor
ON major_class_br.major_minor_id = major_minor.id
INNER JOIN sched_sect_br
ON sched_sect_br.section_id = section.id
INNER JOIN schedule
ON schedule.id = sched_sect_br.schedule_id
INNER JOIN semester
ON semester.id = schedule.semester_id
INNER JOIN office_hours
ON schedule.id = office_hours.schedule_id AND faculty.id = office_hours.faculty_id
This query gets info from all the tables you have in your graph, aside from the event table, that isn't related to any other. But still this query should have more fields on the SELECT (you are only selection fields from the class table, I understand you'd want data from the other 10 tables as well), to do this simple add 'tablename.field' to the list of fields from the SELECT.

Categories