//define index of column
$columns = array(
0 =>'id',
1 =>'employee_name',
2 => 'employee_salary',
3 => 'employee_age'
4 =>'employee_City',
5 => 'employee_State',
6 => 'employee_Pin'
);
$where = $sqlTot = $sqlRec = "";
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( employee_name LIKE '".$params['search']['value']."%' ";
$where .=" OR employee_salary LIKE '".$params['search']['value']."%' ";
$where .=" OR employee_age LIKE '".$params['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT * FROM `employee` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
Help me please, I have 3 tables, all tables has a primary key as table_id how to get data from 3 tables using server side datatables how to implement join query in this code. Here employee_City, employee_State and employee_Pin are stored in second table. Employ personal details Stored in third table. How to join all tables?
I have just take dummy name of table city , state , pincode ..
Try with this query :
$sql = "SELECT id, employee_name, employee_salary, employee_age, employee_City, employee_State, employee_Pin FROM employee LEFT JOIN city ON employee.cityID = city.id LEFT JOIN state ON employee.stateID = state.id LEFT JOIN pincode ON employee.pincodeid = pincode.id ";
if( !empty($params['search']['value']) ) {
$sql .=" WHERE ";
$sql .=" ( employee_name LIKE '%".$params['search']['value']."%' ";
$sql .=" OR employee_salary LIKE '%".$params['search']['value']."%' ";
$sql .=" OR employee_age LIKE '%".$params['search']['value']."%' )";
}
$sql.=" ORDER BY employee_name";
These links will help you make join query:
https://www.sitepoint.com/understanding-sql-joins-mysql-database/
http://www.techonthenet.com/mysql/joins.php
Related
I would like to get data from two tables in MySQL, ordered by date.
$sql = "
SELECT
items.*, invoice.*
FROM
items
JOIN
invoice
ON
items.user_id = invoice.buyer_id
WHERE
items.user_id = '$user_id'"
LIMIT
10
ORDER BY
date;
";
Try with:
$sql = "SELECT *";
$sql .= " FROM items, invoice";
$sql .= " WHERE items.user_id = invoice.buyer_id";
$sql .= " AND items.user_id = '$user_id'";
$sql .= " ORDER BY date DESC";
$sql .= " LIMIT 10";
Also it is better if you use it as a prepared statement instead of having the variable inside the SQL query to avoid SQL injection.
I have this code that (without the WHERE, was working) How do I get it to work with the WHERE clause ?
I just need it to only list lines that is current and max 2 years ahead.
$SQL = "SELECT ";
$SQL .= "SUM(Bookings.Spots) as SUMSPOT, Trips.ID, Bookings.FK_ID, Trips.MaxSpots, ";
$SQL .= "Trips.Tripnr, Trips.StartDate, Trips.EndDate, Trips.StartLocation, ";
$SQL .= "Trips.DestinationDK, Trips.PricePerSpot ";
$SQL .= "FROM Trips WHERE Trips.EndDate >= NOW() AND Trips.EndDate < DATE_ADD(NOW(), INTERVAL 2 YEAR) ";
$SQL .= "LEFT JOIN Bookings on Bookings.FK_ID = Trips.ID ";
$SQL .= "GROUP BY Trips.ID, Bookings.FK_ID ORDER BY Trips.StartDate ASC ";
You need to add the WHERE clause after the LEFT JOIN and before the GROUP tag.
You can check the documentation here for more answers as to where you can put which keyword.
What I'm trying to return in a set: The lessonIDs associated to the userID and schoolID within a given startTime and endTime.
This is to be displayed on a calendar. I only want to display the lessons that are associated to the user viewing it for a selected school within the time range they are viewing on the calendar.
This data is just dummy data to show the table structure and data types.
Lesson Table:
lessonID roomFK startTime endTime
1 2 2014-08-01 13:00:00 2014-08-01 14:00:00
2 3 2014-08-01 13:00:00 2014-08-01 14:00:00
Room Table:
roomID schoolFK
1 1
2 1
3 2
4 2
School Table:
schoolID
1
2
User Table:
userID
1
2
3
Lesson/Teacher Junction Table:
lessonFK teacherFK
1 1
1 2
2 3
What I've tried:
function find_lessons_by_school_id_and_teacher_id_ranged_feed($school_id, $teacher_id, $start, $end) {
global $connection;
$school_id = mysqli_real_escape_string($connection, $school_id);
$teacher_id = mysqli_real_escape_string($connection, $teacher_id);
$start = mysqli_real_escape_string($connection, $start);
$end = mysqli_real_escape_string($connection, $end);
$start = strftime("%Y-%m-%d %H:%M:%S", $start);
$end = strftime("%Y-%m-%d %H:%M:%S", $end);
$query = "SELECT * ";
$query .= "FROM lesson ";
$query .= "JOIN room ON lesson.roomFK = room.roomID ";
$query .= "JOIN school ON room.schoolFK = school.schoolID ";
$query .= "JOIN user ON user.userID = junc_lesson_teacher.teacherFK ";
$query .= "JOIN junc_lesson_teacher ON junc_lesson_teacher.lessonFK = lesson.lessonID ";
$query .= "WHERE room.schoolFK = '{$school_id}' ";
$query .= "AND lesson.startTime >= '{$start}' ";
$query .= "AND lesson.endTime <= '{$end}' ";
$query .= "AND user.userID = '{$teacher_id}' ";
$query .= "ORDER BY lesson.roomFK ASC";
$set = mysqli_query($connection, $query);
return $set;
}
When I run this, mySQL complains about the query statement.
Any input on how to do this properly would be greatly appreciated! Thanks!
The order of your join operations is wrong. You've got to swap the last two ones. Instead of
$query .= "FROM lesson ";
$query .= "JOIN room ON lesson.roomFK = room.roomID ";
$query .= "JOIN school ON room.schoolFK = school.schoolID ";
$query .= "JOIN user ON user.userID = junc_lesson_teacher.teacherFK ";
$query .= "JOIN junc_lesson_teacher ON junc_lesson_teacher.lessonFK = lesson.lessonID ";
write
$query .= "FROM lesson ";
$query .= "JOIN room ON lesson.roomFK = room.roomID ";
$query .= "JOIN school ON room.schoolFK = school.schoolID ";
$query .= "JOIN junc_lesson_teacher ON junc_lesson_teacher.lessonFK = lesson.lessonID ";
$query .= "JOIN user ON user.userID = junc_lesson_teacher.teacherFK ";
because every table you use in a join must be introduced first. By your statement you can't use junc_lesson_teacher to join the user table, so you've got to join junc_lesson_teacher before you join user. Think of your tables as a chain without interrupts.
If you had a moderately sensible naming policy, that query might look like this...
$query = "
SELECT columns
, i
, actually
, want
FROM lesson l
JOIN room r
ON r.room_id = l.room_id
JOIN school s
ON s.school_id = r.school_id
JOIN lesson_teacher lt -- <-- NOTE TABLES SWAPPED AROUND
ON lt.lesson_id = l.lesson_id
JOIN user u
ON u.user_id = lt.teacher_id -- <-- SEE?
WHERE r.school_id = $school_id
AND l.startTime >= '$start'
AND l.endTime <= '$end'
AND u.user_id = $teacher_id
ORDER
BY l.room_id ASC;
";
$set = mysqli_query($connection, $query)
or die(mysqli_error($connection)); -- for development only
instead of
$query = "SELECT * ";
write all of required fields from all tables
$query = "SELECT lesson.roomFK,room.roomID,school.schoolID,room.schoolFK,user.userID,junc_lesson_teacher.teacherFK,junc_lesson_teacher.lessonFK,lesson.lessonID";
As part of my learning OOP PHP, I have made a database object that includes the following method:
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = static::instantiate($row);
}
return $object_array;
}
and I can use this to retrieve and access data from a single table, however when I try to use it with joined tables, the object only gives me the data from the primary table e.g.
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob";
$sql .= " FROM members AS m";
$sql .= " LEFT JOIN mbr_sections AS ms ON m.id = ms.member_id";
$sql .= " LEFT JOIN sections AS s ON ms.section_id = s.id";
$sql .= " ORDER BY s.organisation ASC, s.name ASC, m.lastName ASC, m.firstName ASC";
$sql .= " LIMIT {$per_page} ";
$sql .= " OFFSET {$pagination->offset()}";
$members = Member::find_by_sql($sql);
Using the above query the following code outputs nothing for the s.name field, but all the fields from the members table are correctly listed. I know that the MySQL query is accessing the data, as the ORDER BY statement is correctly sorting the output.
<?php foreach($members as $member): ?>
<tr>
<td><?php echo $member->name;?></td>
<td><?php echo $member->full_name();?></td>
<td><?php echo $member->getAge($member->dob);?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php endforeach; ?>
If I output $members with print_r($members) it only contains the data from the members table, how do I access the data retrieved from the other tables?
Thanks
You need to select them too here:
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob";
$sql .= " FROM members AS m";
$sql .= " LEFT JOIN mbr_sections AS ms ON m.id = ms.member_id";
$sql .= " LEFT JOIN sections AS s ON ms.section_id = s.id";
$sql .= " ORDER BY s.organisation ASC, s.name ASC, m.lastName ASC, m.firstName ASC";
$sql .= " LIMIT {$per_page} ";
$sql .= " OFFSET {$pagination->offset()}";
$members = Member::find_by_sql($sql);
You only selected name, id, firstName, lastName and dob.
Here is an example:
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob, mbr_sections.field_you_want, sections.*";
I have code like this:
function search_keyword(){
$keyword = trim($_POST['keyword']);
$search_explode = explode(" ", $keyword);
$x = 0;
$sql = " ( SELECT name, id_global_info AS id, body AS body, tag AS tag ,info_type_id AS info_type, \"global_info\" AS mytable FROM global_info WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= " ) UNION ALL ";
$sql .= " ( SELECT name, id_person AS id, surname AS body, info AS tag , location AS info_type, \"person\" AS mytable FROM person WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= " ) UNION ALL ";
$sql .= "( SELECT name, id_event AS id, body AS body, caffe_id AS tag , date AS info_type, \"event\" AS mytable FROM event WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= " ) UNION ALL ";
$sql .= "( SELECT name, id_caffe AS id, description AS body, adress AS tag, location_id AS info_type, \"caffe\" AS mytable FROM caffe WHERE ";
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
$sql .= " ) ";
echo $sql;
$q = $this->db->query($sql);
return $q = $q->num_rows() == 0 ? FALSE : $q->result();
}
When I search for exapmle
"mali oglasi"
I get following error:
Error Number: 1064
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'AND name LIKE '%mali%' AND name LIKE '%oglas%' ) UNION ALL (
SELECT name, id_e' at line 1
This is MySQL query it is producing:
( SELECT name, id_global_info AS id, body AS body, tag AS tag ,info_type_id AS info_type, "global_info" AS mytable FROM global_info WHERE name LIKE '%mali%' AND name LIKE '%oglas%' )
UNION ALL
( SELECT name, id_person AS id, surname AS body, info AS tag , location AS info_type, "person" AS mytable FROM person WHERE AND name LIKE '%mali%' AND name LIKE '%oglas%' )
UNION ALL
( SELECT name, id_event AS id, body AS body, caffe_id AS tag , date AS info_type, "event" AS mytable FROM event WHERE AND name LIKE '%mali%' AND name LIKE '%oglas%' )
UNION ALL
( SELECT name, id_caffe AS id, description AS body, adress AS tag, location_id AS info_type, "caffe" AS mytable FROM caffe WHERE AND name LIKE '%mali%' AND name LIKE '%oglas%' )
What seems to be an error?
First thing's first: don't forget to escape your input value. This can be done in your case either on the initial value, or for each iteration of the foreach loop on $each
// If your query() method calls mysql_query()
$keyword = mysql_real_eascape_string(trim($_POST['keyword']));
// Or if query() is mysqli::query()
$keyword = $this->db->real_escape_string(trim($_POST['keyword']));
// Or if this is Codeigniter's API
$keyword = $this->db->escape_like_str(trim($_POST['keyword']));
You need to reset $x at the start of each foreach loop:
// Reset $x to 0 before the start of each of your loops.
$x = 0;
foreach($search_explode as $each){
$x++;
if($x == 1){
$sql .= " name LIKE '%$each%' ";}
else {
$sql .= " AND name LIKE '%$each%' ";
}
}
Note: It is generally advisable to use parameterized queries instead of building the query by concatenation and interpolation. Codeigniter uses ? placeholders for that.
Your query errors reside in the second, third and fourth SELECT statements, as you have WHERE AND name rather than WHERE name