Put a condition for a field within query - php

I have a sql query :
$cond = "";
if($cid >0 )
{
$quali = $this->getCandidatesQualification($cid);
$cond = "WHERE emp_qualification LIKE '%$quali%'";
}
$sql = "SELECT
emp_job_id,emp_job_profie,emp_qualification,emp_experience
FROM
tbl_emp_data
$cond
ORDER BY job_add_date DESC LIMIT 0,10
";
$res = $this->db->returnArrayOfObject($sql,$pgin = 'no', $odr='no');
Now what I want if emp_qualification field is equal to any_graduate I want to select all the jobs for the candidate even if his qualification is say BA .

so modify your WHERE clause to
WHERE emp_qualification LIKE '%$quali%'
OR emp_qualification = 'any_graduate'

$cond = '';
if($cid >0 ) {
if ($this->getCandidatesQualification($cid) != 'any_graduate') {
$cond = "WHERE emp_qualification LIKE '%{$this->getCandidatesQualification($cid)}%'";
}
}
simplified, try this

Related

Selecting rows where out of two columns one is null

Out of two search selections if a visitor select one only there is no search result. Following is my sql query:
$sql = "SELECT * FROM table WHERE column1='$column1' AND column2 ='$column2' ORDER BY id DESC
If I use 'OR' or otherwise I got wrong result in pagination. What should be right coding if a visitor opted only one criteria to search he will get result in first and subsequent pages?
In PHP construct your query:
$where = [];
$params = [];
if (!empty($column1)) {
$where[] = 'column1 = :column1';
$params[':column1'] = $column1;
} else {
$where[] = 'column1 IS NULL';
}
if (!empty($column2)) {
$where[] = 'column2 = :column2';
$params[':column2'] = $column2;
} else {
$where[] = 'column2 IS NULL';
}
if (!empty($where)) {
$pdo
->prepare("SELECT * FROM table WHERE ".implode(' AND ', $where))
->execute($params);
}
If you allow selection only by one column, remove else parts
A fast solution is that you can put the filters into a variable checking if the values of $column1 or $column2 it's filled and add after that in the SELECT clause:
$where_column = 'WHERE ';
if ($column1 != false)
$where_column .= "column1='$column1'";
if ($column2 != false) {
if ($where_column != 'WHERE') {
$where_column .= "AND column2='$column2'";
else
$where_column = "column2='$column2'";
}
}
$sql = "SELECT * FROM table $where_column ORDER BY id DESC

Search Form Multi Input

I have a search form with 2 select fields and one input, total 3 options, so i created some if statements, depending of each fields are set it haves is own query, but its not working well, is all buggy, the results doesn't get right, it gets mixed up with the statements queries, it's not getting right.
Here is my code for the search form result:
$keywords = $_GET["Keywords"];
$location = $_GET['Location'];
$jobtype = $_GET["Category"];
if (isset($location) && empty($jobtype) && empty($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location'
ORDER BY id_job DESC";
}elseif(isset($location) && isset($jobtype) && empty($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location' AND
jobType_en = '$jobtype'
ORDER BY id_job DESC";
}elseif(isset($location) && isset($jobtype) && isset($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location' AND
jobType_en = '$jobtype' AND
title_en LIKE '%$keywords%'
ORDER BY id_job DESC";
}elseif(empty($location) && isset($jobtype) && empty($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
jobType_en = '$jobtype'
ORDER BY id_job DESC";
}elseif(empty($location) && isset($jobtype) && isset($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
jobType_en = '$jobtype' AND
title_en LIKE '%$keywords%'
ORDER BY id_job DESC";
}elseif(empty($location) && isset($jobtype) && isset($keywords)){
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1' AND
jobType_en = '$jobtype' AND
title_en LIKE '%$keywords%'
ORDER BY id_job DESC";
}
else{
$sql_jobs = "SELECT * FROM jobs
WHERE
active = '1'
ORDER BY id_job DESC";
}
$consultaJob = mysql_query($sql_jobs);
You need to simplify the code:
$sql = "SELECT * FROM jobs
WHERE
active = '1' AND
country = '$location' ";
$order = "ORDER BY id_job DESC";
$where = "";
if( isset( $jobtype ) { $where .= " AND jobType_en = '$jobtype'"; }
if( isset($keywords) { $where .= " AND title_en LIKE '%$keywords%'" };
$sqlx = $sql . $where . $order;
You are obviously processing $jobtype and $keywords earlier on. In this processing you should be setting some default values to make later processing easier.
$jobtitle = (isset( $_GET['jobtitle'] ) ) ? $_GET['jobtitle'] : "";
$keywords= (isset( $_GET['keywords'] ) ) ? $_GET['keywords'] : "";
This way you can use:
if( $jobtitle != '') { .... }
You may want to try strlen() rather than isset or empty
otherwise you have to use both isset() and empty()
empty() does not generate a warning if the variable does not exist.
strlen() will return zero on NULL and ''.
You can set minimum lengths by changing the zero to a higher value.
elseif(strlen($location) > 0 && strlen($jobtype) > 0 && strlen($keywords) > 0 ){
If the submitted values are text inputs then you may need the trim also:
elseif(strlen(trim($location)) > 0 && strlen(trim($jobtype)) > 0 && strlen(trim($keywords)) > 0 ){

MySQL/phpMyAdmin Query Row Count (1 row) vs mysql_num_rows' Count (0 row count)

Here's the code in question:
<?php // If search option is selected
include 'db_connect.php';
database_connect();
$limit = 5; // No of result per page
$criteria = 1; // Search criteria
$allResults=array(); // Array of results
$searchOption = $_REQUEST['searchoption'];
$searchField = $_REQUEST['searchfield'];
$searchField = str_replace('+',' ', $searchField) ;
$dbcolumn = "user_id";
$dbtable = "profiles";
$order = "user_id";
if ($searchField){
if ($searchOption == "People"){
$words = explode(' ', trim($searchField));
$searchField = $words[0];
$dbcolumn = "profile_display_name";
$dbtable = "profiles P, user_roles U, roles R";
$order = "profile_first_name";
$criteria = " P.user_id = U.user_id AND U.role_id = R.role_id
AND(`profile_display_name` LIKE '%$searchField%'
OR `profile_first_name` LIKE '%$searchField%'
OR `profile_last_name` LIKE '%$searchField%'
OR `profile_email` LIKE '%$searchField%'
OR `profile_state` LIKE '%$searchField%'
OR `profile_zip_code` LIKE '%$searchField%'
OR `business_summary` LIKE '%$searchField%')";
}
//focus here folks (my comment to readers, not actual part of code
else if ($searchOption == "Jobs"){
$dbcolumn = "job_title";
$dbtable = "job_postings";
$order = "`created_date` DESC";
$criteria = "(`job_title` LIKE '%$searchField%'
OR `job_description` LIKE '%$searchField%'
OR `client_name` LIKE '%$searchField%'
OR `city` LIKE '%$searchField%'
OR `state_abbr` LIKE '%$searchField%'
OR `zipcode` LIKE '%$searchField%')
AND `job_status` = 'Open'";
}
else if($searchOption == "News"){
$dbcolumn = "";
$dbtable = "";
$order = "";
$criteria = "1";
}
//Pagination
if($dbtable){
$rs = mysql_query("SELECT * FROM $dbtable WHERE $criteria");
$no_of_rec = mysql_num_rows($rs);
$page = ($_REQUEST['page'])? $_REQUEST['page'] : 1;
$no_of_pages = ceil($no_of_rec/$limit);
$offset = ($page - 1)*$limit;
echo "pagination #rows: $no_of_rec ";
}
}
// If the user enters a value in the search
if ($searchField){
$resultcount = 0;
if($dbtable) {
// Search query executes
$query = "SELECT * FROM $dbtable WHERE $criteria ";
$query .= "ORDER BY $order ";
$query .= "LIMIT $offset, $limit";
$result = mysql_query($query) or die(mysql_error());
$resultcount = mysql_numrows($result);
echo "query: $query ";
echo "result: $result ";
echo "result count: $resultcount ";
}
if ($resultcount <= 0){
$allResults[] = "No match found";
}
else{
// Get search results from database
while ($row = mysql_fetch_array($result)){
$allResults[]=$row;
}
}
}
else{
$allResults[] = "No value entered";
}
?>
Here's what the echo statements show:
pagination #rows: 0 query: SELECT * FROM job_postings WHERE (`job_title` LIKE '%Help Wanted%' OR `job_description` LIKE '%Help Wanted%' OR `client_name` LIKE '%Help Wanted%' OR `city` LIKE '%Help Wanted%' OR `state_abbr` LIKE '%Help Wanted%' OR `zipcode` LIKE '%Help Wanted%') AND `job_status` = 'Open' ORDER BY `created_date` DESC LIMIT 0, 5 result: Resource id #36 result count: 0
(I left the echo printouts as they were so you can see what I see and how I see it.)
When I run the query in MySQL and phpMyAdmin, I get the row I'm looking for.
Can someone explain why mysql_numrows() thinks there are 0 results?
I've checked PHP.net and I have Googled this as well. No luck so far.
Many thanks.
there is a mistype in this line
$resultcount = mysql_numrows($result);
you should call mysql_num_rows()
you can use this code alternatively
$isExist = mysql_query("Select count(id) from ...");
$r = mysql_fetch_array($isExist);
if($r['COUNT(id)'] > 0){
//item exists
}else{
//item doesnt exist
}

SQL Construction & PHP

I'm sure this is an easy question.
If you want to produce SQL with php for a search query. So you have say 5 criteria which are all optional and may or may not be inputted by the user. You cannot guarantee any of them.
When it comes to making the SQL in php you can use :
So if they exist then you can use AND for the 4 last criteria.
But for the first criteria if you have that as a WHERE if that one is not selected then the SQL just is a list of ANDs with no starting WHERE.
Is there an easy answer?
Code I've Written :
$sql = "
SELECT *
FROM Request, Rooms
WHERE Day = ".$Day." ";
if($ModCode != ''){
$sql .="AND ModCode = ".$ModCode." ";
}
if($StartTime != ''){
$sql .="AND StartTime = ".$StartTime." ";
}
if($Length != ''){
$sql .="AND Length = ".$Length." ";
}
if($Room != ''){
$sql .="AND Request.RoomID = Rooms.RoomID ";
$sql .='AND Rooms.RoomName = "'.$Room.'" ';
}
if($Room == '' && $Park != ''){
$sql .="AND Request.RoomID = Rooms.RoomID ";
$sql .='AND Rooms.Park = "'.$Park.'" ';
}
And now I want the bit WHERE Day = $Day to be optional like the others.
Cheers
You could store all criterias in an array and then implode AND between them:
if(!empty($array)) {
$where_part = "WHERE " . implode(" AND ", $array);
}
Update:
$cond = array();
if($ModCode != ''){
$cond[] = "ModCode = ".$ModCode;
}
if($StartTime != ''){
$cond[] = "StartTime = ".$StartTime;
}
if($Length != ''){
$cond[] = "Length = ".$Length;
}
if($Room != ''){
$cond[] = "Request.RoomID = Rooms.RoomID";
$cond[] = 'Rooms.RoomName = "'.$Room.'"';
}
if($Room == '' && $Park != ''){
$cond[] = "Request.RoomID = Rooms.RoomID";
$cond[] = 'Rooms.Park = "'.$Park.'"';
}
if(!empty($cond)) {
sql .= "WHERE " . implode(" AND ", $cond);
}
I dont think this would work.
For this kind of JOIN you always need a WHERE statement with a join condition.
And after adding it, the question will make sense no more.
However, if you need conditional JOIN as well as conditional WHERE, you had to state it in the question.
Anyway, the method is quite similar.
Store your wheres in an array and only impode the array into the query if its not empty.
Something like this;
$where = array();
//build up your where's in an array
$where[] = "searchField1='blah'";
$where[] = "searchField2='foo'";
//make your query and on the where only implode the array if its not empty else return null
$sqlQuery = "
Select
*
FROM
yourTable
".(empty($where)==false ? " WHERE ".implode(" AND ", $where) : null)."
ORDER BY x
";
where 1 = 1
and (name = ? or ? is null)
and (age = ? or ? is null)
question marks are just value placeholders. you get the point.
use prepared statements and bound parameters.
anyway, each of the parenthesized predicate conditions will evaluate to true of the placeholder value is null. make sure you differentiate between the sql keyword null, and "empty" or "falsy" values like 0 or empty string. The above requires type null.
I think I understand what you mean. You could split the query like so.
$sql = "SELECT * FROM `table` WHERE ";
$sql .= ($val1 == 1) ? "`field` = 'value' " : "1 = 1 ";
$sql .= ($val2 == 2) ? "AND `field` = 'value'" : "AND 1 = 1";
Edit: A quick fix would be to add a clause that would always be true.
In MySQL you have MATCH ... AGAINST
Like so:
SELECT id, header, message FROM table WHERE MATCH(header,message) AGAINST ('".mysql_real_escape_string($search)."' IN BOOLEAN MODE)
You can combine MATCH .. AGAINST with any other WHERE-clause, like:
WHERE id > 1000 AND MATCH (...) AGAINST ('searchstring' IN BOOLEAN MODE) AND date < NOW()
This does, however, require FULLTEXT searches to be possible, so it isn't very useful on TEXT-columns in InnoDB-tables for as far as I know. But it is the perfect solution to do searches in MyISAM tables, and you can use it on VARCHAR()-columns.

MySQL: Combining two repetitive queries to make WHERE clause dynamic

How can I combine these two queries into one so I don't have to repeat the same lines again and again?
if(empty($cat_id))
{
$sql = "
SELECT *
FROM root_category_contacts
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql);
}
else
{
$sql = "
SELECT *
FROM root_category_contacts
WHERE root_category_contacts.cat_id != ?
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql,array($cat_id));
}
I don't need WHERE clause when I don't have the cat_id.
Is it feasible?
Test if ? is null or equals cat_id. Something like this:
Edit based on xdazz's comment. And assuming that cat_id > 0
$sql = "
SELECT *
FROM root_category_contacts
WHERE root_category_contacts.cat_id != ?
ORDER by cat_order ASC"
if(empty($cat_id)) {
$cat_id = 0;
}
$items_category = $connection->fetch_all($sql,array($cat_id));
if(empty($cat_id)) $where = "";
else $where = "WHERE root_category_contacts.cat_id != '$cat_id'"
$sql = "
SELECT *
FROM root_category_contacts
$where
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql);

Categories