The third query doesn't work but the first two query in the if statement doesn't have any problem. I'm trying to create an advanced search in PHP with date and filters. Is there a limit in using "AND" in sql?
Any tips to help me get a better sql statement than this?
$sql2 = "SELECT * FROM `work` WHERE `remarks` = 'PENDING' AND `College` IN($college12)";
if (!empty($search) && !empty($criteria)) {
$sql2 .= "AND `$criteria` LIKE '%$search%' LIMIT $start,$limit";
}
if (!empty($dateFrom) && !empty($dateTo)) {
$sql2 .= "AND Date_App >= '$dateFrom' AND Date_App <= '$dateTo' LIMIT $start,$limit";
}
if (!empty($dateFrom) && !empty($dateTo) && !empty($search) && !empty($criteria)) {
$sql2 .= "AND Date_App >= '$dateFrom' AND Date_App <= '$dateTo' AND `$criteria` LIKE '%$search%' LIMIT $start,$limit";
}
Related
I have been staring at this code so long it is starting to bleed together. So let's get a couple things out of the way:
I am a low-moderate level SQL user and am still learning the best ways to accomplish queries and such
I have been building a PHP based quote-generator tool that ties in with an SQL database
Now, here is what I am trying to accomplish:
I would like to have pagination with the results of quotes that have been created with a status that is NOT "Dead", "Duplicate", or "Signed" and the ID does NOT equal 999 (because I wanted the quotes to jump to 1000 and I did not build the database correctly at first)
Here is what I have accomplished:
I was able to create the basic structure and it works just fine on page 1... then it all goes sideways. I was thinking that it was something to do with my count(*) query, but that seems fine - well functional, at least:
$countQry = "SELECT COUNT(*)
from needsassessment
WHERE ID <> 999
AND status <> 'Dead'
AND status <> 'Duplicate'
AND status <> 'Signed'";
$countResult = $mysqli->query($countQry);
while($rowQ = mysqli_fetch_array($countResult)) {
$totalRows = $rowQ[0];
$each = ceil($totalRows/$limit);
$where = "WHERE ID > 0";
if ($totalRows == 0) {
echo "You have not created any quotes.";
}
}
$limit = 15;
if (isset($_GET['q']) && $_GET['q'] !== "") {
$offset = $_GET['q'];
} else {
$offset = 0;
}
$query = "SELECT * FROM needsassessment $where
where $and
AND ID <> 999
AND NOT status = 'Dead'
AND NOT status = 'Duplicate'
AND NOT status = 'Signed'
ORDER BY ID DESC LIMIT $offset, $limit";
$result = $mysqli->query($query);
$row_cnt = mysqli_num_rows($result);
if ($row_cnt == 0) {
echo "You have not created any quotes."; die;
}
if (!isset($each)) {
$each = $row_cnt/$limit;
}
if ($each > 1) {
echo "<ul class='pagination'>";
for($i=1,$y=0;$i<=$each,$y<=($each-1);$i++,$y++) {
echo "<li><a";
if ($offset == ($y*15)) {echo ' class="active"';}
echo " href='?q=".($y*15)."'>$i</a></li>";
}
echo "</ul>";
}
Okay, so here are my questions:
I saw someone say that using PHP's mysqli_num_rows() is wrong and
that I should use SQL's COUNT(*). Why? Does it have a different result or take longer?
What is going on with page's
2 and 3? When I do a row count it says it sees 15 rows but only some
are showing. I have some records (i.e. those with a status of
"Signed" or "Dead") that are excluded from this list and I was
thinking that may have been the issue, but it doesn't seem to matter
on the first page.
What is the difference - if there is one -
between "NOT" and "<>" for checking records?
If you have any suggestions or if I have done anything blatantly wrong or inefficiently please let me know so I can correct it :)
Thanks to all that make Stack Overflow AWESOME!
EDIT:
There certainly was some code missing:
if (!isset($sst)) {
$where = "";
$sst = "";
$countQry = "SELECT COUNT(*) from needsassessment WHERE ID <> 999 AND status <> 'Dead' AND status <> 'Duplicate' AND status <> 'Signed'";
$countResult = $mysqli->query($countQry);
while($rowQ = mysqli_fetch_array($countResult)) {
$totalRows = $rowQ[0];
$each = ceil($totalRows/$limit);
$where = "WHERE ID > 0";
if ($totalRows == 0) {echo "You have not created any quotes.";}
}
}
else {
if ($option !== "*") {
$where = "WHERE ".$option." LIKE '%".$sst."%'";
}
if ($option == "*") {
$where = "WHERE status LIKE '%".$sst."%' OR title LIKE '%".$sst."%' OR propType LIKE '%".$sst."%' OR pSType LIKE '%".$sst."%' OR createDate LIKE '%".$sst."%'";
}
$offset = 0;
}
if ($_SESSION['admin'] >= 1) {
$and = "";
}
else {
$and = "AND creatorID = '".$_SESSION['user']."'";
}
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 ){
I have now three different PHP pages that contain almost the same information so to be able to reduce this to one page I need to have a php variable inside the mysql query.
Today it is like this:
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY yearstart DESC, mndstart DESC";`
I need that the " AND Bruk = '1'" is removed from this query-line if i put ?nobruk=no in the adressbar. Is this possible and if so, how?
You don't want to (and can't) put an if inside your query; you want to use an if to create your query based on some condition. There are lots of ways to write this, one of which is
if (!empty($_GET['nobruk'])) {
$query1 = "SELECT ... WHERE `Kategori` = '1' ORDER BY ...";
}
else {
$query1 = "SELECT ... WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY ...";
}
Another way, which is shorter and involves the ternary operator, is
$includeBruk = empty($_GET['nobruk']);
$query1 = "SELECT ... WHERE `Kategori` = '1' ".
($includeBruk ? "AND `Bruk` = '1' " : "").
"ORDER BY ...";
A simple if statement:
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori` = '1'";
if ($_GET['nobruk']!='no') {
$query1.=" AND `Bruk` = '1'";
}
$query1.= " ORDER BY yearstart DESC, mndstart DESC";
Like this :
<?php
$query = ($_REQUEST['nobruk'] == "no") ? "SELECT * FROM `Yrker` WHERE `Kategori` = '1' ORDER BY yearstart DESC, mndstart DESC": "SELECT * FROM `Yrker` WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY yearstart DESC, mndstart DESC";
echo $query;
?>
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori`='1' ".($_GET['nobruk'] === 'no' ? "" : "AND `Bruk`='1' ")."ORDER BY yearstart DESC, mndstart DESC";
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
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);