MySQL: Combining two repetitive queries to make WHERE clause dynamic - php

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);

Related

The limiting of php/mysql outcome from the table(probably easy thing)

Good day,
I have a problem with following code, I have to limit companies ID_CL (it`s outcome). I want to limit the display to the only one ID_CL (one because , right now it displays everything) is it possible ?
Sorry for stupid question, I usually don't work with mysql/php
{
//$size_h =1;
list($list_num, $size_w, $size_h) = $this->getImageDefSize('list');
//$table = TB_JOB." jb LEFT JOIN ".TB_CL." cl USING(".ID_CL.") ";
$table = TB_JOB." jb LEFT JOIN ".TB_CL." cl USING(".ID_CL.") ";
$field = "jb.".ID_JOB.", jb.job_code, jb.shop_name, jb.job_name, jb.intro, jb.video_url, jb.salary, jb.area_0, jb.area_1, jb.area_2, jb.biz_0, jb.biz_1, jb.biz_2, jb.emid, jb.tel, jb.email, jb.access, jb.nenshu_range, jb.sv_1, jb.company, jb.worktime, jb.holiday";
$field .= ", jb.rail_1_0, jb.rail_1_1, jb.rail_1_2, jb.rail_2_0, jb.rail_2_1, jb.rail_2_2, jb.free_1_0, jb.free_1_1, jb.free_2, jb.free_3, jb.moddate, jb.regdate, jb.contents, jb.qualification,jb.zip,jb.pfid,jb.address1,jb.address2";
$field .= ", cl.".ID_CL.", cl.cl_name, cl.business, cl.email AS client_email ";
//$field .= ", cl.".ID_CL.", cl.cl_name, cl.business, cl.email AS client_email ";
if (! empty($_SESSION["srch"]["new"])) {
$od = " ORDER BY jb.setdate DESC, cl.rank, jb.jobid ASC";
} else {
$od = " ORDER BY cl.rank, jb.moddate DESC, jb.jobid ASC";
}
//$total = $this->countTB($table, ID_JOB, $this->wh);
$total = $this->countTB($table, ID_JOB, $this->wh);
\
if ($total > 0) {
// $_SESSION["srch"]["idlist"] = $this->arrayTB($table, ID_JOB, $this->wh.$od);
$_SESSION["srch"]["idlist"] = $this->arrayTB($table, ID_JOB, $this->wh.$od);```
Yes, you can use MySQL LIMIT for this purpose.
According to your query, After , jb.jobid ASC you should add LIMIT 1
This will help you.

Where and Order By clause not working

So this piece of code doesn't work and I can't figure it out.
$productid = (isset($_REQUEST['productId'])) ? $_REQUEST['productId'] : '';
$query = "SELECT * FROM products WHERE productId = '$productid' ORDER BY rand() limit 3";
Perhaps try:
$productid = (isset($_REQUEST['productId'])) ? $_REQUEST['productId'] : '';
if ($productid != ''){
$query = "SELECT * FROM products WHERE productId = '$productid' ORDER BY rand() limit 3";
} else {
$query = "SELECT * FROM products ORDER BY rand() limit 3";
}
This should return all products if the productId isn't coming over.

PHP Optimized query call if nothing is selected

I am trying to make my coding more efficient and I am stuck at how to tell the query to display all the categories if nothing is selected.
I have 15 categories that the user can chose from, if none is selected, display all items. Rather than doing AND .. AND .. AND 15 times if nothing is selected, is there a smarter way for this?
This will work for one category selection:
$cate = mysql_query("SELECT * FROM `posts` ORDER BY `id` ASC");
while($row = mysql_fetch_assoc($cate)){
if($user_data['category'] === $row['id']) {
echo '<li>'.$row['name'].'</li>';
}
}
$category_list = "AND `category_id` = '".$user_data['category']."'";
You should generate your query dynamically
// General query
$query = "SELECT * FROM `posts`";
// If category selected
if ($user_data['category'] != 0) {
$query .= " WHERE `category_id` = '".$user_data['category']."'";
}
// Order
$query .= " ORDER BY `id` ASC";
// Run query
$cate = mysql_query($query);
Or it can be simplified using Ternary Operator:
// Generate query
$query = "SELECT * FROM `posts` ".($user_data['category'] != 0 ? "WHERE `category_id` = '".$user_data['category']."'" : "" )." ORDER BY `id` ASC";
// Run query
$cate = mysql_query($query);

if argument inside mysql query

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";

Put a condition for a field within query

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

Categories