Search for user in 3 different tables that have different columns - php

I'm having a hell of a time with this. I have 3 tables of users. They are in different tables because they have different columns depending on the type of user they are.
Now to log in to the site I'm trying to select the user's email and all the other values that correspond to him. Based on some feedback from other users here I wrote my query like this:
$query = "SELECT id, position_id, first_name, last_name, email ";
$query .= "FROM pims ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1 ";
$query .= "UNION ALL SELECT id, district_id, position_id, first_name, last_name, email ";
$query .= "FROM dms ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1 ";
$query .= "UNION ALL SELECT * ";
$query .= "FROM users ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1";
But I get a "Database query failed" message. The query worked fine when I had only one SELECT statement, so I know it's this query that's not working. Any ideas how to fix it?

Doing union all should have the same number of columns in all queries.
$query = "SELECT id, 'garbage_data' AS district_id, position_id, first_name, last_name, email ";
$query .= "FROM pims ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1 ";
$query .= "UNION ALL ";
$query .= "SELECT id, district_id, position_id, first_name, last_name, email ";
$query .= "FROM dms ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1 ";
$query .= "UNION ALL ";
$query .= "SELECT id, district_id, position_id, first_name, last_name, email ";
$query .= "FROM users ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1";
In case you have a missing column. You can add none existent data like:
'garbage_data' AS district_id
This will show a string garbage_data which is just there to make the column count the same.
It can be anything, It can even be '' AS district_id.

First off the number and type of columns need to be the same in a union query. Second I would suggest you to make a view for that and then use the view for convenience since I don't think this is the only spot you will need such a query.
$query = "SELECT id, '' as district_id, position_id, first_name, last_name, email ";
$query .= "FROM pims ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1 ";
$query .= "UNION ALL SELECT id, district_id, position_id, first_name, last_name, email ";
$query .= "FROM dms ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1 ";
$query .= "UNION ALL SELECT id, district_id, position_id, first_name, last_name, email ";
$query .= "FROM users ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "AND com_code IS NULL ";
$query .= "LIMIT 1";

Related

Inner join in server side data table with php

//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

FULL TEXT search with normal search

Im trying to make a query that will do a full text search with 2 additional conditions. The full text part works fine. I tried these so far, and both are not working:
$query = "SELECT * FROM table ";
$query .= "WHERE MATCH(title) ";
$query .= "AGAINST('".$title."') ";
$query .= "AND state='".$state."' ";
$query .= "AND county='".$county."' ";
$query .= "LIMIT 5 ";
$query = "SELECT * FROM table ";
$query .= "WHERE MATCH(title) ";
$query .= "AGAINST('".$title."') ";
$query .= "MATCH(state) AGAINST('".$state."') ";
$query .= "MATCH(county) AGAINST('".$county."') ";
$query .= "LIMIT 5 ";
I just tried this from the comments, but I get an error 1064 near %$state%:
$query = "SELECT * FROM table ";
$query .= "WHERE MATCH(title) ";
$query .= "AGAINST('".$title."') ";
$query .= "AND state LIKE %".$state."% ";
$query .= "AND county LIKE %".$county."% ";
$query .= "LIMIT 5 ";
$query = "SELECT * FROM table ";
$query .= "WHERE title ";
$query .= "LIKE %".$title."% ";
$query .= "AND state LIKE %".$state."% ";
$query .= "AND county LIKE %".$county."% ";
$query .= "LIMIT 5 ";

mysql_fetch_array not working for 1 row query result

My query works fine. but wen trying get unique value from the table mysql fetch array not work.
this is my sql
A-2815 is the item code of the vehicle. this field is unique. Expecting result is item_code A-2815 's vehicle details.
$sql = "SELECT vehicle.id, item_code, make, model, vehicle_type, color, showroom_id, ";
$sql .= "adding_user_Id, approved, image_1 ";
$sql .= "FROM images, vehicle ";
$sql .= "WHERE vehicle.id=images.item_id ";
$sql .= "AND (item_code LIKE '%A-2815%' ";
$sql .= "OR make LIKE '%A-2815%' ";
$sql .= "OR model LIKE '%A-2815%' ";
$sql .= "OR vehicle_type LIKE '%A-2815%' ";
$sql .= "OR color LIKE '%A-2815%' ";
$sql .= "OR showroom_id LIKE '%A-2815%') ";
$sql .= "AND activate=1 ";
$sql .= "AND type_of_image=1 ";
this is my php code.
<?php
$query = mysql_query($sql);
while($result = mysql_fetch_array($query)){
echo $result['item_code'];
echo $result['make'];
echo $result['model'];
echo $result['vehicle_type'];
echo $result['color'];
echo $result['showroom_id'];
}
?>
this working ok when results are more then 1 row. but problem is when result is 1 row then it is not working.
while ($result = mysql_fetch_array($query, MYSQL_ASSOC)) {
// assoc
echo $result['item_code'];
}
MySQLi solution for this
$connect = mysqli_connect('localhost', 'root', 'pwd', 'dbname');
$sql = "select * from sometable";
$query = mysqli_query($connect, $sql);
while ($result = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
// assoc
echo $result['item_code'];
}

PHP - Run Two Mysql Queries That Use "SELECT" Through a Drop-down Menu

Basically, I have a drop-down menu that has two options - 'All' & 'Top Rated'.
<select class="dropdown">
<option value="all">All</option>
<option> value="toprated">Top Rated</option>
</select>
I want to run this query through the 'All' option...
$myQuery = "SELECT Attraction.*, Type.TypeName, Rating.RatingUrl ";
$myQuery .= "FROM Attraction ";
$myQuery .= "INNER JOIN Type ON Attraction.Type = Type.TypeID ";
$myQuery .= "INNER JOIN Rating ON Attraction.AttractionID = Rating.AttractionID ";
$myQuery .= "WHERE Attraction.Type = 4 ";
$myQuery .= "ORDER BY Name ";
$result = mysql_query($myQuery);
if (!$result) {
die('Query error: ' . mysql_error());
}
And the this query through the 'Top Rated' option...
$myQuery = "SELECT Attraction.*, Type.TypeName, Rating.RatingUrl ";
$myQuery .= "FROM Attraction ";
$myQuery .= "INNER JOIN Type ON Attraction.Type = Type.TypeID ";
$myQuery .= "INNER JOIN Rating ON Attraction.AttractionID = Rating.AttractionID ";
$myQuery .= "ORDER BY Rating DESC, Name ";
$result = mysql_query($myQuery);
if (!$result) {
die('Query error: ' . mysql_error());
}
Can anyone generate the php structure I would need for this to work...
If anyone can help that would be great!
I recommend this tutorial for PHP and this mysqli reading
Also, check what WebChemist said:
Not ok:
<option> value="toprated">Top Rated</option>
Ok:
<option value="toprated">Top Rated</option>

Query Improvement mysql

Hi Guys i have this query and it is super slow.
If you can understand the code how can i possibly combine the two queries into one
or how can i possibly make this query faster.
this is the code
$strSQL = "SELECT user_status_history.*, queues_config.extension FROM user_status_history ";
$strSQL .= "LEFT JOIN queues_config ON user_status_history.skillset = REPLACE(queues_config.grppre, \":\", \"\") ";
$strSQL .= "WHERE user_status_history.status_id = 9 "; # outbound call
$strSQL .= "AND DATE_FORMAT(status_time, '%Y-%m-%d') = '$check_date' ";
if ($i==1)
$strSQL .= "AND TIME_FORMAT(status_time, '%H:%i') >= '$cboHrFrom:$cboMinFrom' ";
else if (strtotime($check_date) == strtotime($end_date))
$strSQL .= "AND TIME_FORMAT(status_time, '%H:%i') <= '$cboHrTo:$cboMinTo' ";
$strSQL .= "AND queues_config.extension = '$cboSkillSet' ";
if ($cboGroup!='' && $strAgentGroup!='') $strSQL .= "AND user_status_history.user_id IN (".$strAgentGroup.") ";
$strSQL .= "ORDER BY user_status_history.user_id, user_status_history.status_time ";
$rs2 = &$cn->Execute($strSQL);
while (!$rs2->EOF)
{
$strSQL = "SELECT status_time, time_to_sec(timediff(status_time, '".$rs2->fields['status_time']."')) AS timesecs FROM user_status_history ";
$strSQL .= "LEFT JOIN queues_config ON user_status_history.skillset = REPLACE(queues_config.grppre, \":\", \"\") ";
$strSQL .= "WHERE status_time > '".$rs2->fields['status_time']."' ";
$strSQL .= "AND user_id = '".$rs2->fields['user_id']."' ";
$strSQL .= "AND queues_config.extension = '".$rs2->fields['extension']."' ";
$strSQL .= "ORDER BY status_time LIMIT 1;";
$rs3 = &$cn->Execute($strSQL);
if (!$rs3->EOF)
{
$sum_talk_sec = $sum_talk_sec + $rs3->fields['timesecs'];
}
$rs3->Close();
$rs2->MoveNext();
}
$rs2->Close();
1
Check out there are table indexes for
user_status_history.status_id
user_status_history.user_id
2
these are difficult for optimizer. Try get rid of these
LEFT JOIN queues_config ON user_status_history.skillset = REPLACE(queues_config.grppre, \":\", \"\") ";
LEFT JOIN queues_config ON user_status_history.skillset = REPLACE(queues_config.grppre, \":\", \"\") ";
3
Get rid of the loop query.
Fetch all IDs from query1 to an array and create one query for them all:
"SELECT user_id, status_time, time_to_sec(timediff(status_time, '".$rs2->fields['status_time']."')) AS timesecs FROM user_status_history ";
...
AND user_id IN (id1, id2, id3 ... )
4 (From DCOder )
Convert these the other way around. Use PHP to create mysql datetime fields.
$strSQL .= "AND DATE_FORMAT(status_time, '%Y-%m-%d') = '$check_date' ";
-- >
preg_match('/^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$/', $check_date, $regs );
$enddate = date('Y-m-d', mktime( $hour=6, $min=0, $sec=0, $mon=$regs[2], $day=$regs[3]+1, $year=$regs[1] ));
$strSQL .= " AND status_time > '$check_date' AND status_time <= '$enddate' ;
$strSQL .= "AND TIME_FORMAT(status_time, '%H:%i') >= '$cboHrFrom:$cboMinFrom' ";
-- > $strSQL .= " AND status_time >= '$check_date $cboHrFrom:$cboMinFrom:00' ";
$strSQL .= "AND TIME_FORMAT(status_time, '%H:%i') <= '$cboHrTo:$cboMinTo' ";
-- > $strSQL .= " AND status_time <= '$check_date $cboHrTo:$cboMinTo:59' ";

Categories