Reputation: 35
i want to fetch all records if my catid is null and fetch specific id data if catid is provided using same query here is my code
$catid=$_GET['cat'];
if($_GET['cat'] = '' || $_GET['cat'] = null ){
$sel="select * from listings where `stat`='Y' and order by `sno` ".$pagination->getLimitSql();
}else{
$sel="select * from listings where `stat`='Y' and `category`='{$catid}' order by `sno` ".$pagination->getLimitSql();
}
$result=mysql_query($sel);
$listProducts = array(); // create a variable to hold the information
while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
$listProducts[] = $row; // add the row in to the results (data) array
};
Upvotes: 2
Views: 182
Reputation: 2561
try below one:
<?php
$sel = !empty($_GET['cat']) ? "select * from listings where `stat`='Y' and `category`='{$catid}' order by `sno` ".$pagination->getLimitSql() : "select * from listings where `stat`='Y' and order by `sno` ".$pagination->getLimitSql();
$result=mysql_query($sel);
$listProducts = array(); // create a variable to hold the information
while(($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
$listProducts[] = $row; // add the row in to the results (data) array
};
Upvotes: 1
Reputation: 2553
You can replace =
with ==
or you can do following with isset()
and empty()
functions.
Apart from that you can do following to remove duplication from your code.
$catid=$_GET['cat'];
$sel = "select * from listings where `stat`='Y'";
if(isset($_GET['cat']) && !empty($_GET['cat'])){
$sel .= "and `category`='{$catid}'";
}
$sel .= " and order by `sno` ".$pagination->getLimitSql();
Upvotes: 0
Reputation: 21
You should use like this
if(!$_GET['cat']) {
$sel="select * from listings where `stat`='Y' and order by `sno` ".$pagination->getLimitSql();
} else {
$sel="select * from listings where `stat`='Y' and `category`='{$catid}' order by `sno` ".$pagination->getLimitSql();
}
Upvotes: -3
Reputation: 8606
Please replace =
with ==
if($_GET['cat'] = '' || $_GET['cat'] == null ){
A better approach would be this:
if (isset($_GET['cat']) && !empty($_GET['cat'])) {
Upvotes: 3