Tariq Ali
Tariq Ali

Reputation: 35

i want to use same query for fetch all record and specific id records in php mysql

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

Answers (4)

lazyCoder
lazyCoder

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

Pankit Gami
Pankit Gami

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

mukesh_patel
mukesh_patel

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

Indrasis Datta
Indrasis Datta

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

Related Questions